[英]Template Specialization for Private Types
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.
有一个 trait 类可以专门用于提供这些 trait。
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.但是,专业化只能发生在我的类无法访问的
namespace
或全局范围内。
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?也许可以将专业化声明为
friend
类?
You could make class template Trait
the friend of class A
via template friend declaration .您可以通过模板朋友声明使类模板
Trait
成为类A
朋友。
template <typename T> struct Trait {};
class A
{
struct Secret
{};
template <typename T>
friend struct Trait;
};
Or refer to the full specialization of A::Secret
.或者参考
A::Secret
的完整专业化。
template <typename T> struct Trait {};
class A
{
struct Secret
{};
friend struct Trait<A::Secret>;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.