也許你可以使用下面的技巧。鑑於這些簡單的類型特點:
template<bool b, typename T, typename U>
struct conditional { typedef T type; };
template<typename T, typename U>
struct conditional<false, T, U> { typedef U type; };
template<typename T, typename U>
struct is_same { static const bool value = false; };
template<typename T>
struct is_same<T, T> { static const bool value = true; };
你可以寫出如下類和專業的成員函數:
class ReturnTypeSpecialization
{
public:
template<typename T>
typename conditional<is_same<T, float>::value, int, T>::type
Item();
};
// Normally just return the template type
template<typename T>
typename conditional<is_same<T, float>::value, int, T>::type
ReturnTypeSpecialization::Item() { return T(); }
// When a float is specified, return an int
template<>
int ReturnTypeSpecialization::Item<float>() { return 1.0f; }
簡單的測試程序(使用C++ 11只是爲了驗證):
int main()
{
ReturnTypeSpecialization obj;
static_assert(std::is_same<decltype(obj.Item<bool>()), bool>::value, "!");
static_assert(std::is_same<decltype(obj.Item<float>()), int>::value, "!");
}
這是live example。
你想達到什麼目的? – didierc 2013-04-09 20:37:52
我想要一個函數來返回作爲模板參數提供的類型,除非在特殊情況下我希望函數返回不同的類型。 – 2013-04-09 20:40:51
只是爲了記錄:如果模板參數是從參數的類型中推導出來的,而不是明確指定的,則完成返回不同類型的更簡單的方法是使用函數重載。 (當然這個例子在這個例子中不起作用,因爲沒有參數) – jorgbrown 2017-05-09 16:03:41