2013-08-19 50 views
-4

是否有可能通過使用另一個輔助類來專門化模板來抽象此行爲(使用邏輯或專有化類型)而不使用 。模板規範

當我將int或char傳遞給同一個類時需要特別說明。

template<typename K> 
struct test 
{ 

}; 

template<> 
struct test<int or char> 
{ 

}; 

謝謝。

CB

+3

嗯,什麼行爲? – patrickvacek

+1

什麼幫手類? – PlasmaHH

+0

我想在指定模板時獲得像邏輯或行爲的東西。 –

回答

2

您可以使用C++ 11個型性狀本(或者,如果你還沒有C++ 11,使用Boost的類型特徵):

#include <type_traits> 

template <typename K, bool special = std::is_same<K, char>::value || std::is_same<K, int>::value> 
struct A 
{ 
    // general case 
}; 

template <typename K> 
srtuct A<K, true> 
{ 
    //int-or-char case 
}; 
+0

謝謝Angew。這正是我想要的。我不知道爲什麼人們在不知道的時候投票。 :) :) –

+0

@cowboy說實話,我半信半疑地猜到你在做什麼。這個問題原來的形式還不太清楚。 – Angew

+0

是的,這是真的。我可以在發佈前檢查它們。感謝您的建議。 –

0

你的問題太含糊了,但我想你說的是這樣的嗎?

template <typename T> 
struct A 
{ 
    //... 
} 

template<B> 
struct A 
{ 
    //... 
} 

在這種情況下,你應該指定如何模板結構及其行爲的模板某些特定類型的

0

C++的支持部分專業化。爲您解決問題最簡單的方法(我想這是你的問題)是偏特結構測試int或字符,鼻翼:

template <typename T> struct test 
{ 
    // For arbitrary type T... 
}; 

template <> 
struct test<int> 
{ 
    // definition for when T = int 
}; 

template <> 
struct test<char> 
{ 
    // definition for when T = char 
}; 
+0

實際上不是。謝謝。我想知道是否可以在專注模板的同時獲得邏輯或行爲。或者它不可能,因爲它是編譯時間規範。 –