Friend template functions (in classes without templates), C ++

If I have a non-template class (that is, "normal") and you want to have a template name function, how can I write it without causing a compiler error? Here is an example illustrating what I'm trying to do:

template <class T> void bar(T* ptr); class MyClass // note that this isn't a template class { private: void foo(); template <class T> friend void bar(T*); // ERROR: compiler gives me all kinds of grief }; template <class T> void bar(T* ptr) { if (ptr) { MyClass obj; obj.foo(); } } 

I am using Visual Studio 2005, and the specific error I give you is error C2063 , stating that "bar" isnโ€™t a function. What needs to be done differently here?

+4
source share
2 answers

Are you sure you sent the error message? The following (using Visual Studio 2005) works fine for me:

 #include <iostream> template <class T> void bar(T* ptr); class MyClass // note that this isn't a template class { private: void foo(); template <class T> friend void bar(T*); // ERROR: compiler gives me all kinds of grief }; void MyClass::foo() { std::cout << "fooed!" << std::endl; } template <class T> void bar(T* ptr) { if (ptr) { MyClass obj; obj.foo(); } } int _tmain(int argc, _TCHAR* argv[]) { int someObj = 1; bar(&someObj); return 0; } 
+4
source

This is more a workaround than a fix, but have you tried to list your specializations as friends?

0
source

All Articles