I got trouble in creating special instance of member template function of non-template class. I have, for example, class A with template member function F:
class A
{public:
template <class T> int F (T arg)开发者_C百科 const;
....
}
and want to have a special instance of this template function F for type B:
class B;
...
template <> void A::F (B arg) const //GOOD!
and it works perfectly, until appears that B is a template itself!
This code
template <class T> class B ...
...
template <> void A::F (B<T> arg) const //error, T undeclared
as well as
template <class T> class B ...
...
template <class T> template <> void A::F (B<T> arg) const //error, too many templates
gives compiling error.
The second trouble is, how to declare this special instance (or template instance at whole) to be friend function of class B? (Is does not work even if B is not a template).
class B
{friend template <> void A::F (B arg) const // error
// as well as
template <> friend void A::F (B arg) const // error
}
Is there a way to write code in a way I'm going to at all or it is not possible?
You're attempting to create a partial specialization for a function template, which is illegal. What you can do is simply create an overload.
To create a friend, you merely have to use the correct syntax.
The following compiles without errors.
template <typename T>
struct B {};
struct A
{
template <typename T>
void F(T arg) const;
template <typename T>
void F(B<T> arg) const;
template <typename T>
friend void G(B<T> arg);
template <typename T>
friend struct B;
};
精彩评论