2012-11-08 57 views
-1

我對std :: enable_if很陌生,想知道如何使用它。 我有一個模板類:std :: enable_if第二次詢問

template<int a, int b> 
class foo { 
    int c; 
} 

我只希望模板有成員c當

a = 5. 

我該怎麼做,使用的std :: enable_if? 這是一個正確的情況下使用std :: enable_if?

+0

這是怎麼從你的[第一個問題]不同(http://stackoverflow.com/questions/13260581/c-stdenable-if)?也就是說,爲什麼你不能使用在這個例子中被接受的答案中建議的技巧? – jogojapan

+0

第一個是關於執行a + b遵循一些規則。這是關於包括一些基於關於 – WhatABeautifulWorld

回答

3

您可以使用部分專業化。不需要std::enable_if

//primary template 
template<int a, int b> 
class foo 
{ 
     //whatever 
}; 

//partial specialization 
template<int b> 
class foo<5,b> //when a = 5, this specialization will be used! 
{ 
    int c; //it has member c 
}; 

用法:

foo<1,3> f1; //primary template is used 
foo<5,3> f2; //partial specialization is used 
+0

的一些規則的c在這種情況下,很多代碼是重複的? – WhatABeautifulWorld

+1

@WhatABeautifulWorld:然後正確地提出問題。在問題中提供更多信息。另外,如果有幫助,您可以嘗試使用基本公共類模板。 – Nawaz