2009-07-22 45 views
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; 
     ... 
    } 
+0

如果您是基于值进行专门化,那么它暗示着这些特定值有一些特殊之处。如果您在整个模板中将它们用作常规值,并且只在几个地方将它们视为特殊值,则可能会将特殊行为抽象为较小的专用类模板,从而使大模板成为完全通用和未专用的模板。这有点难以分辨,所以你可以扩大你的问题,使其更“真实”? – 2009-07-22 06:59:51

+0

我认为这个问题足够真实。我有基于协议版本实现特定行为的现有基类。以前它有一个成员返回协议版本 - 因为该成员不再可用,所以有一个记录方法在输出中包含协议版本。我可以硬编码的价值,但我想知道是否有更好的方法。被接受的答案提供了很好的方法 - 我实际上在其他地方以类似的方式使用特征 - 获取参数类型,但意图是相同的。 – stefanB 2009-07-22 07:37:32

回答

16

这类问题可以解决通过拥有一套独立的“特质”结构。

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

+1不错,谢谢 – stefanB 2009-07-22 04:53:31

1

不是一个真正的回答你的问题,但你可以列举出来,即:

enum{ 
specialisationMajor=4, 
specialisationMinor=0 
}; 

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

我试图避免定义另一组变量......这是具有这些模板参数的美丽,我不''通常想要访问的值......但从来不想,但谢谢 – stefanB 2009-07-22 00:23:52

相关问题