Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare all instantiated class of a template to be friend mutually? [duplicate]

Say I have a template (helper) class, and I want to make all the instantiated classes of the template to be friend (so I can hide some static member function as private, even if they switch template arguments occasionally inside).

Like this:

template </* some types */>
class Foo {
    template </* same as above types */>
    friend class Foo</* template arguments */>;
    // ...
};

However, this won't compile since gcc warns me that I'm specializing some template which is not allowed (must appear at namespace scope). I'm not trying to specializing anything...

Is there any way to do it?


Originally, since there are many many arguments, I was trying to use variadic template to save some typing, but that's considered specialization by compiler. Though later I switched back to type all arguments, the explicit specialization is invoked (the <> is kept).

The very original code:

template <class... Ts>
friend class Foo<Ts...>;
like image 748
YiFei Avatar asked Dec 24 '22 22:12

YiFei


1 Answers

Yes you can, just use the correct template friends declaration syntax. e.g. (explanations are written in the comments)

template <T>
class Foo {
    // declare other instantiations of Foo to be friend
    // note the name of the template parameter should be different with the one of the class template
    template <typename X>
    friend class Foo; // no </* template arguments */> here, otherwise it would be regarded as template specialization
};
like image 57
songyuanyao Avatar answered Apr 28 '23 13:04

songyuanyao