问题
If I have a non-template (i.e. "normal") class and wish to have a template friend function, how do I write it without causing a compiler error? Here is an example to illustrate what I am 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'm using Visual Studio 2005, and the specific error I'm given is error C2063, stating that "bar" isn't a function. What needs to be done differently here?
回答1:
Are you sure what you've posted gives the error? 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;
}
回答2:
This is more of a workaround than a fix, but have you attempted to list the specializations as friends?
来源:https://stackoverflow.com/questions/458795/friend-template-functions-in-non-template-classes-c