Search code examples
c++templatesfriend

Can we add a friend class based on template parameter?


I wonder whether the below tricky situation is possible:

Suppose I have a template class template <typename DTYPE> class A{};, where DTYPE is supposed to be one of uint8_t, uint16_t, etc. I want to add a friend class to A, but this friend class differs for each DTYPE alternative. Further, suppose the friend classes for different DTYPE values are not instantiations of another template class, but independent classes.

Is there a way to do it?


Solution

  • You can add template "proxy" class FriendOfA and specialize it for whatever type you need:

    // actual friends
    class FriendUint8 {};
    class FriendUint16 {};
    
    template<typename T> struct FriendOfA;
    
    template<>
    struct FriendOfA<uint8_t> {
        typedef FriendUint8 type;
    };
    
    template<>
    struct FriendOfA<uint16_t> {
        typedef FriendUint16 type;
    };
    
    // optional helper
    template <typename T>
    using FriendOfA_t = typename FriendOfA<T>::type;
    
    template<class T>
    class A {
        friend typename FriendOfA<T>::type;
        // or simply
        friend FriendOfA_t<T>;
    };