ste*_*anB 10 c++ templates template-specialization
是否可以在专用模板类中访问非类型模板参数的值?
如果我有专门化的模板类:
template <int major, int minor> struct A {
void f() { cout << major << endl; }
}
template <> struct A<4,0> {
void f() { cout << ??? << endl; }
}
Run Code Online (Sandbox Code Playgroud)
我知道上面的情况,硬编码值4和0而不是使用变量很简单,但我有一个更大的类,我是专门的,我希望能够访问值.
在A <4,0>中是否可以访问major
和minor
值(4和0)?或者我必须在模板实例化时将它们分配为常量:
template <> struct A<4,0> {
static const int major = 4;
static const int minor = 0;
...
}
Run Code Online (Sandbox Code Playgroud)
And*_*erd 16
这种问题可以通过一组单独的"特征"结构来解决.
// A default Traits class has no information
template<class T> struct Traits
{
};
// A convenient way to get the Traits of the type of a given value without
// having to explicitly write out the type
template<typename T> Traits<T> GetTraits(const T&)
{
return Traits<T>();
}
template <int major, int minor> struct A
{
void f()
{
cout << major << endl;
}
};
// Specialisation of the traits for any A<int, int>
template<int N1, int N2> struct Traits<A<N1, N2> >
{
enum { major = N1, minor = N2 };
};
template <> struct A<4,0>
{
void f()
{
cout << GetTraits(*this).major << endl;
}
};
Run Code Online (Sandbox Code Playgroud)