function template prototypes

Jan 5, 2009 at 2:31pm
how do i create a template function prototype such that i do not have to define it everytime before i use it?
Jan 5, 2009 at 4:01pm
I don't think you can. You could include the entire template function body in the header; although this technically is wrong, I have heard that compilers will allow it because template must be defined wherever they are used. I know for certain that VC++ 2008 allows it...
Jan 5, 2009 at 4:06pm
You mean something like this?
1
2
3
4
5
6
7
8
9
//header file
template <typename T>
T f(T a,T b);

//cpp file
template <typename T>
T f(T a,T b){
	return a+b;
}

That's not possible. Template functions have to be declared and defined in the same file.
This is one of the very few things I hate about C++.

EDIT: Nope. VC++ doesn't allow it, thankfully.
Last edited on Jan 5, 2009 at 4:14pm
Jan 5, 2009 at 7:25pm
EDIT: Nope. VC++ doesn't allow it, thankfully.


I just tried to compile a program with a full template definition in the header file and received no errors.

Perhaps you thought I meant VC allows your example? If that's the case, that's not what I meant (sorry for being confusing).
Jan 6, 2009 at 1:09am
i mean if i can put something like a normal function prototype near the start of the program and define it after I use it in main within the same file?
Jan 6, 2009 at 4:03am
As long as the declaration and the definition are in the same file, there's absolutely no problem.
Jan 6, 2009 at 5:13am
then my question would be how do I do the declaration/prototype of a function template?
Jan 6, 2009 at 7:27am
@helios: You can actually split definition and implementation into two files, but it ain't pretty, and as far as I understand it is also not recommended:

1
2
3
4
5
6
7
8
9
10
11
12
13
// Filename: Point.h
template<typename T>
class Point
{
  public:
    T getX();
    T getY();
  private:
    T myX;
    T myY;
}

#include "Point.tmpl" 


1
2
3
4
5
6
//filename: Point.tmpl
template<typename T>
T Point::getX() { return myX; }

template<typename T>
T Point::getY() { return myY; }


Jan 6, 2009 at 12:31pm
I'm sure the compiler will give at least two flying ***** that the definition is in a different physical file but included with the declaration.

The point of spreading a program across several files is, aside from organization, not having to recompile the entire code every time a change is made to any part of it.
Jan 7, 2009 at 1:09am
so how do i declare the prototype in the same file?
Jan 7, 2009 at 1:34am
I did give an example in my second post.
Topic archived. No new replies allowed.