开发者

C++ special instance of template function for some type which is a template class itself

开发者 https://www.devze.com 2022-12-15 19:49 出处:网络
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:

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;
};
0

精彩评论

暂无评论...
验证码 换一张
取 消