如何特化一个模板sub-class?
How to specialize a template sub-class?
我正在尝试将模板 class 专门化到另一个 class 中,但编译器不允许。该代码在 class Foo 之外工作,但在内部不工作,我希望 struct Bla 对 class Foo.
私有
class Foo {
template<typename ... Ts> struct Bla;
template<> struct Bla<> { static constexpr int x = 1; };
};
error: explicit specialization in non-namespace scope 'class Foo'
你根本做不到。该错误很好地总结了它。 Class 模板只能在命名空间范围内特化。 class Foo
不是命名空间。
您可以在 class 之外执行此操作,按照标准 [temp.class.spec] 中的示例:
A class template partial specialization may be declared or redeclared in any namespace scope in which its
definition may be defined (14.5.1 and 14.5.2). [ Example:
template<class T> struct A {
struct C {
template<class T2> struct B { };
};
};
// partial specialization of A<T>::C::B<T2>
template<class T> template<class T2>
struct A<T>::C::B<T2*> { };
A<short>::C::B<int*> absip; // uses partial specialization
—end example ]
您不能在 class 内进行专精,使用:
class Foo {
public: // so we can test it easily
template<typename ... Ts> struct Bla;
};
// specialize it outside the class
template<> class Foo::Bla<> { static constexpr int x = 1; };
int main()
{
std::cout << Foo::Bla<>::x;
}
我正在尝试将模板 class 专门化到另一个 class 中,但编译器不允许。该代码在 class Foo 之外工作,但在内部不工作,我希望 struct Bla 对 class Foo.
私有class Foo {
template<typename ... Ts> struct Bla;
template<> struct Bla<> { static constexpr int x = 1; };
};
error: explicit specialization in non-namespace scope 'class Foo'
你根本做不到。该错误很好地总结了它。 Class 模板只能在命名空间范围内特化。 class Foo
不是命名空间。
您可以在 class 之外执行此操作,按照标准 [temp.class.spec] 中的示例:
A class template partial specialization may be declared or redeclared in any namespace scope in which its definition may be defined (14.5.1 and 14.5.2). [ Example:
template<class T> struct A { struct C { template<class T2> struct B { }; }; }; // partial specialization of A<T>::C::B<T2> template<class T> template<class T2> struct A<T>::C::B<T2*> { }; A<short>::C::B<int*> absip; // uses partial specialization
—end example ]
您不能在 class 内进行专精,使用:
class Foo {
public: // so we can test it easily
template<typename ... Ts> struct Bla;
};
// specialize it outside the class
template<> class Foo::Bla<> { static constexpr int x = 1; };
int main()
{
std::cout << Foo::Bla<>::x;
}