是否可以在专门的模板类中访问非类型模板参数的值?
如果我有专门化的模板类:
template <int major, int minor> struct A {
void f() { cout << major << endl; }
}
template <> struct A<4,0> {
void f() { cout << ??? << endl; }
}
我知道在上述情况下,硬编码值 4 和 0 很简单,而不是使用变量,但我有一个更大的类,我专门研究它,我希望能够访问这些值。
是否可以在 A<4,0> 中访问 major
和 minor
值(4 和 0)?或者我是否必须在模板实例化时将它们分配为常量:
template <> struct A<4,0> {
static const int major = 4;
static const int minor = 0;
...
}
最佳答案
这类问题可以通过一组单独的“Traits”结构来解决。
// 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;
}
};
关于c++ - 是否可以在专门的模板类中访问非类型模板参数的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1162401/