加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:39:28 所属栏目:百科 来源:网络整理
导读:是否可以在专用模板类中访问非类型模板参数的值? 如果我有专门的模板类: template int major,int minor struct A { void f() { cout major endl; } } template struct A4,0 { void f() { cout ??? endl; } } 我知道上述情况,硬编码值4和0是简单的,而不是使
是否可以在专用模板类中访问非类型模板参数的值?

如果我有专门的模板类:

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>访问主要和次要值(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; 
    }   
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读