10

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

如果我有专门的模板类:

   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;
       ...
   }
4

4 回答 4

17

这种问题可以通过拥有一组单独的“特征”结构来解决。

// 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; 
    }   
};
于 2009-07-22T03:19:47.827 回答
1

不是您问题的真正答案,但您可以列举它们,即:

enum{
 specialisationMajor=4,
 specialisationMinor=0
};

template <> struct A<specialisationMajor,specialisationMinor> {
    static const int major = specialisationMajor;
    static const int minor = specialisationMinor;
    ...
}
于 2009-07-22T00:17:40.213 回答
0

不,您无权访问专门的非类型模板参数。但这里有一种在实施中不重复自己的方法f

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

   template <int major, int minor>
   struct A : public f_impl<major, minor>
   {};

   template <> struct A<4,0> : public f_impl<4,0>
   {};

对于这个例子,一个人不会获得太多,因为一个人需要写4,0两次(--所以你可以cout在你的 OP 中写第二次)。但是,如果您使用模板参数有更多功能,它就会开始发挥作用。

于 2019-09-10T21:09:30.753 回答
0

不是你的问题的真正答案,但下面的想法帮助了我一次:

#include <iostream>

template <int major, int minor, int= major, int= minor> struct A {
    void f() { std::cout << major << '\n'; }
};

template <int major, int minor> struct A<major, minor, 4, 0> {
    void f() { std::cout << major << ':' << minor << '\n'; }
};

int main()
{
    A<3, 3>().f();
    A<4, 0>().f();
}
于 2018-10-08T09:17:56.937 回答