c++ - 是否可以在专门的模板类中访问非类型模板参数的值?

标签 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; }
   }

我知道在上述情况下,硬编码值 4 和 0 很简单,而不是使用变量,但我有一个更大的类,我专门研究它,我希望能够访问这些值。

是否可以在 A<4,0> 中访问 majorminor 值(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/

相关文章:

c++ - 访问没有赋值的 Linux 环境变量

C++0x 移动构造函数陷阱

虚函数上的 C++ 多态性

c++ - 命名空间被视为类型

c++ - 将非模板函数指针传递给模板方法

c# - VisualStudio 多项目模板

c++ - 对类模板的静态变量的 undefined reference

c++ - 嵌套模板类特化的语法

c++ - 使用特殊类中的类模板的内部类型

c# - 如何根据单元格背景颜色更改 WPF DataGrid 单元格小部件背景颜色?