Archived

This topic is now archived and is closed to further replies.

nRob

C++: Template Member Functions

Recommended Posts

nRob    122
Does anyone know if it is possible to have a template function inside a class, something like this:- class CClass { public: void NormalFunction(); template void TemplateFunction(T*); }; I have tried it, and the compiler (MSVC++6) will let me create an instance of such a class, but I could find no syntax that would actually run the template function.

Share this post


Link to post
Share on other sites
Miserable    606
I don''t see why it shouldn''t work. Of course, as you may already know, VC++ 6.0 is notoriously bad with templates. You might want to try it in another compiler.

Share this post


Link to post
Share on other sites
daerid    354
In VC6, if my memory serves, you can have template member functions, but only with classes that aren''t already templates.

VC.NET suffers no such drawbacks.

If it compiles fine, try calling the function. If that doesn''t work, try explicitly telling the compiler which templated function to call, like so:

int i = 4;
int* pi = &4;
obj.TemplateFunction(pi);

Share this post


Link to post
Share on other sites
paulc    132
You can have template member functions. The thing to be aware of is that the compiler has to work out what the template parameter is from the function call at compile time. You can''t instantiate the function like you would a normal template class, you just have to use it with a valid template parameter and let the compiler work things out.

Share this post


Link to post
Share on other sites
cgoat    132
As long as you''re using a pointer for your example function, the compiler should be able to figure out which function you want. The following compiles and runs fine on MSVC++ 6.0:


  
#include <cstdio>


class TestClass
{
public:
template<typename T> void TemplateFunction(T* p_pObj)
{
printf("TemplateFunction Called\n");
}
};


int main(int argc, char *argv[])
{
int *pInt;
void *pVoid;
float *pFloat;

TestClass oClass;
oClass.TemplateFunction(pInt);
oClass.TemplateFunction(pVoid);
oClass.TemplateFunction(pFloat);

return 0;
}

Share this post


Link to post
Share on other sites
cgoat    132
quote:
Original post by daerid
In VC6, if my memory serves, you can have template member functions, but only with classes that aren't already templates.


That's not true. Change my example to
template<typename X> class TestClass  
and
TestClass<int> oClass; 
and it still works.

Unless that problem was fixed in a service pack... I do have the latest VC6 service pack installed.



[edited by - cgoat on March 18, 2003 3:16:04 PM]

Share this post


Link to post
Share on other sites