3

I have a generic algorithm that needs to access its template type's traits. There is a trait class that can be specialized for providing these traits.

When using this algorithm within my class, I'd like to use it with a private type defined within the class.

However, specialization can only happen within namespace or global scope where my class is inaccessible.

class A
{
    struct Secret 
    {};
};

template <typename T> struct Trait {};

// Inaccessible type ----vvvvvvvvv
template <> struct Trait<A::Secret> // Specialize for  PRIVATE type A::Secret
{ 
    A::Secret magic_value() { return{}; } // ERROR: 'A::Secret': cannot access private struct declared in class 'A'
};  

Is it possible to somehow specialize a template with a private type, at least in scopes where this type is accessible?

Maybe it's possible to declare the specialization a friend class?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Adi Shavit
  • 16,743
  • 5
  • 67
  • 137

1 Answers1

8

You could make class template Trait the friend of class A via template friend declaration.

template <typename T> struct Trait {};
class A
{
    struct Secret 
    {};

    template <typename T>
    friend struct Trait;
};

Or refer to the full specialization of A::Secret.

template <typename T> struct Trait {};
class A
{
    struct Secret 
    {};

    friend struct Trait<A::Secret>;
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405