2009-07-22 102 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

相關問題