2013-04-23 137 views
2

我想添加一個成員函數,以防我的類的最後一個模板參數顯式設置爲某個值。我不明白如何重新使用以前定義的代碼。什麼,我想獲得編譯部分類模板專業化

簡單的例子:

template <int A, int B, int C> 
struct S 
{ 
    void fun() {} 
}; 

template <int A, int B> 
struct S<A,B,0> 
{ 
    void fun1() {} 
}; 

template <int A> 
struct S<A,0,0> 
{ 
    void fun2() {} 
}; 

int main() 
{ 
    S<0,0,0> s; 
    s.fun(); 
    s.fun1(); 
    s.fun2(); 
    return 0; 
} 

我需要找到與C++編譯器03一個解決方案。

回答

5

正因爲如此,您的專業是一種非專業化,因爲它不擅長任何的主模板的參數:

template<int A, int B> 
struct S<A,B> // ... 
//  ^^^ 
//  Does not really specialize the primary template, 
//  no specialized pattern is introduced here 

你可以嘗試重寫這樣說:

template<int A> // <== Only the first template parameter of the primary 
       //  template is unconstrained in the pattern we want to 
       //  express (the second template argument shall be 1) 
struct S<A,1> : public S<A,0> 
//  ^^^    ^
// Specializes!   Something meaningful should go here, 
//       but that actually depends on the real 
//       class templates you are using and their 
//       semantics 
{ 
     void fun1() {} 
}; 

或者,如果您的目標僅僅是有條件地添加一個成員函數,則可以使用SFINAE約束而不是專門化:

#include <type_traits> // <== Required for std::enable_if<> 

template <class T = void> 
//     ^^^^ 
//     The function's return type here 
typename std::enable_if<B == 1, T>::type 
//      ^^^^^^ 
//      Your condition for the function's existence 
fun1() 
{ 
    // ... 
} 

這是一個live example演示這種技術。

+0

將默認值的模板參數提供專業化? – 2013-04-23 10:11:15

+0

@Koushik:取決於你的意思。在主模板中,你可以指定'int B = 1',然後'S '匹配'S '特殊化(用'A = X'),如果這就是你要求的 – 2013-04-23 10:12:27

+0

是的,那就是我所要求的。無法構思更好的句子對不起。 – 2013-04-23 10:17:08