Template Specialization for Private Types

拈花ヽ惹草 提交于 2021-01-27 12:31:23

问题


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?


回答1:


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>;
};


来源:https://stackoverflow.com/questions/38761076/template-specialization-for-private-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!