0

Let's say I have some template class which needs an access to private fields of any its specialization:

template<std::size_t SIZE> class Buffer {
    template<std::size_t N> friend class Buffer<N>;

    ...
};

This code doesn't compile:

<source>:4:42: error: specialization of 'template<long unsigned int SIZE> class Buffer' must appear at namespace scope
    4 |     template<std::size_t N> friend class Buffer<N>;
      |                                          ^~~~~~~~~

How can I achieve this behavior?

kiv_apple
  • 491
  • 3
  • 13
  • It would be much simpler to just make all the members public. That’s effectively what making every template instance a friend does, since users can write specializations of your friend template. – Pete Becker Nov 15 '22 at 22:29

1 Answers1

2

Consider the same declaration without the friend specifier:

template<std::size_t N> class Buffer<N>;

That is not a declaration of a (primary) class template Buffer, but a declaration of a partial specialization of Buffer.

A declaration of the (primary) class template itself looks like this:

template<std::size_t N> class Buffer;

So add the friend specifier to that and you friend the class template itself, which implies friending all specializations of it:

template<std::size_t SIZE> class Buffer {
    template<std::size_t N> friend class Buffer;

    //...
};
user17732522
  • 53,019
  • 2
  • 56
  • 105