Discussion:
Is it possible to have a non-inline template function in class?
(too old to reply)
SVC
2008-07-18 21:38:23 UTC
Permalink
Hi,

It is always possible to declare an inline template function within a class.

Is it possible to have a non-inline template function within a class?

How do we call it?

For example:

in Header file
--------------
class TMyClass
{
public:
template <class T> bool MyFunc(T a, T b) ;
};

extern TMyClass MyClass;

In Cpp file
----------
TMyClass MyClass;
//..
//...
template <class T> bool MyClass::MyFunc(T a, T b)
{
// ... do stuff
return true;
}


In another Cpp, file
-------------------
How do we call this member function?

MyClass.MyFunc<int>(i,j); // does not work (compiler error)
MyClass.template<int>MyFunc(i,j); // does not work (compiler error)

Thanks,
S
Remy Lebeau (TeamB)
2008-07-18 22:34:36 UTC
Permalink
Post by SVC
Is it possible to have a non-inline template function within a class?
The implementation of the template does not need to be inlined inside the
template declaration, but it does need to be located somewhere inside the
same context that declares the template. Every source file that includes
your header file needs to include the template implementation as well. You
cannot declare the template in a header file and then define the body in a
.cpp file (which is what you are trying to do). What you can do, however,
is move the body to a .ipp file that the header file includes via an
#include statement, ie:

--- TMyClass.h ---

#ifndef TMyClassH
#define TMyClassH

class TMyClass
{
public:
template <class T> bool MyFunc(T a, T b) ;
};

extern TMyClass MyClass;

#include "TMyClass.ipp"

#endif


--- TMyClass.cpp ---

#include "TMyClass.h"

TMyClass MyClass;


--- TMyClass.ipp ---

template <class T> bool TMyClass::MyFunc(T a, T b)
{
// ... do stuff
return true;
}
Post by SVC
In another Cpp, file
-------------------
How do we call this member function?
Like you already tried:

MyClass.MyFunc<int>(i,j);

Or, if 'i' and 'j' are both 'int' variables, you can drop the
specialization:

MyClass.MyFunc(i, j);


Gambit

Loading...