Function Templates within Class possible ??
I've just discovered Function Templates and would like to implement it within my class. Is this possible?
I've tried doing something like this:
--
class MyClass
{
public:
template <class T> char WriteActionFile(T &incVar)
}
template <class T> char MyClass::WriteActionFile(T &incVar)
{
cout << sizeof T << endl;
}
void main(..)
{
MyClass myObj;
long val=10;
myObj.WriteActionFile(val);
}
--
What happens is VC++6 returns back the error message:
==
error C2893: Failed to specialize function template 'char __thiscall MyClass::WriteActionFile(T &)' - With the following template arguments:
'char'
==
Ok what did i do wrong? I've tried other combos but cant seem to get function templates to work for a specific class? Does this mean function templates can only be implemented within the global namespace? Ideally i would like to have the template prototype within the class declaration and the definition within the source file, that is, I would prefer not to have to inline the function body into the class declaration. :)
You can do it - no problem
also in VC 6++. All you have to do, is impolement the function INLINE, like so:
class MyClass
{
template <class X> int func (X x) { ..... }
};
Re: Function Templates within Class possible ??
hello,
I am facing quite similar problem but with one difference. Some of the template functions are working and not producing compilation errors while some are not. Also, the template functions which are compiling does not contain the use of template variable T.
I am using VC++6
thanks in advance.
Regards
Vikas
Re: Function Templates within Class possible ??
If a template func doesn't use T arguments, the VS6 compiler will not be able to instantiate it. It's in the MSDN. Send a dummy T argument to solve this:
template <class T>
T func(T dummy = 0) {...}
I used the default value '0'. There is a drawback though: it REQUIRES that all T types used here will have a ctor that looks like this: T(int) {...}
This is true even if you use something other than 0, like NULL, which will require a ctor: T(void*) { ...} and so on.
If you don't want to use this trick, move to GNU or VS7 :-)
About the other thing you said, I didn't understand what compiles and what doesn't. Please send some code.