问题描述
我有一个通用算法,需要访问其模板类型的特征.有一个特质类可以专门提供这些特质.
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.
但是,专业化只能在无法访问我的类的 namespace
或全局范围内进行.
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?
也许可以将专门化声明为 friend
类?
Maybe it's possible to declare the specialization a friend
class?
推荐答案
您可以通过模板朋友声明.
template <typename T> struct Trait {};
class A
{
struct Secret
{};
template <typename T>
friend struct Trait;
};
或参考 A :: Secret
的完整专业知识.
Or refer to the full specialization of A::Secret
.
template <typename T> struct Trait {};
class A
{
struct Secret
{};
friend struct Trait<A::Secret>;
};
这篇关于专用类型的模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!