Bitrex Bitrex - 6 days ago 4
C++ Question

Declare a variadic template class a friend of a simple template class

I have a first class with a variadic template parameter pack like so:

template <typename T, typename... Args>
class A
{
public: ...etc


I have a second class with a simple template parameter:

template <typename T>
class B
{
public: ...etc


The first type arguments to both templates will be the same.

I would like to declare class A a friend of B so that A can access a couple private methods of B. How to achieve this?

Answer

If you are OK with unconditional friendship (i.e. every A is a friend of B, even if the T parameter doesn't match), then you can simply use friend class:

template <typename T>
class B;

template <typename T, typename... Args>
class A
{
public:
    void test(B<T>& b);
};

template <typename T>
class B
{
    template <typename, typename...>
    friend class A;

    int priv;
};

template <typename T, typename... Args>
void A<T, Args...>::test(B<T>& b){ (void) b.priv; } 

The following code will compile:

int main()
{
    B<int> b;
    A<int, float> a;
    a.test(b);
}

wandbox example