是否可以在专门的模板类中访问非类型模板参数的值? [英] Is it possible to access values of non-type template parameters in specialized template class?

查看:125
本文介绍了是否可以在专门的模板类中访问非类型模板参数的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to access values of non-type template parameters in specialized template class?

如果我有专门的模板类:

If I have template class with specialization:

   template <int major, int minor> struct A {
       void f() { cout << major << endl; }
   }

   template <> struct A<4,0> {
       void f() { cout << ??? << endl; }
   }



我知道上面的情况很容易硬编码值4和0而不是使用变量,但是我有一个更大的类,我专业化,我想能够访问的值。

I know it the above case it is simple to hardcode values 4 and 0 instead of using variables but what I have a larger class that I'm specializing and I would like to be able to access the values.

在A< 4 ,0>访问主要次要值(4和0)?或者,我必须将它们作为常量分配给模板实例化:

Is it possible in A<4,0> to access major and minor values (4 and 0)? Or do I have to assign them on template instantiation as constants:

   template <> struct A<4,0> {
       static const int major = 4;
       static const int minor = 0;
       ...
   }


推荐答案

这种问题可以通过一组单独的Traits结构来解决。

This kind of problem can be solved by having a separate set of "Traits" structs.

// 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; 
    }   
};

这篇关于是否可以在专门的模板类中访问非类型模板参数的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆