function template prototypes

how do i create a template function prototype such that i do not have to define it everytime before i use it?
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...
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
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).
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?
As long as the declaration and the definition are in the same file, there's absolutely no problem.
then my question would be how do I do the declaration/prototype of a function template?
@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; }


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.
so how do i declare the prototype in the same file?
I did give an example in my second post.
Topic archived. No new replies allowed.