C++: Template Member Functions

Started by
4 comments, last by nRob 21 years, 1 month ago
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.
Advertisement
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.
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); 
daerid@gmail.com
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.
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;}  
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]

This topic is closed to new replies.

Advertisement