問(wèn)題描述
我想專門化一個(gè)函數(shù)模板,以便返回類型根據(jù)模板參數(shù)的類型而變化.
I would like to specialize a function template such that the return type changes depending on the type of the template argument.
class ReturnTypeSpecialization
{
public:
template<typename T>
T Item();
};
// Normally just return the template type
template<typename T>
T ReturnTypeSpecialization::Item() { ... }
// When a float is specified, return an int
// This doesn't work:
template<float>
int ReturnTypeSpecialization::Item() { ... }
這可能嗎?我不能使用 C++11.
Is this possible? I can't use C++11.
推薦答案
由于專業(yè)化必須與返回類型的基本模板一致,您可以通過(guò)添加返回類型特征"來(lái)實(shí)現(xiàn),您可以使用一個(gè)結(jié)構(gòu)專門化并從以下位置繪制真正的返回類型:
Since the specialization has to agree with the base template on the return type, you can make it so by adding a "return type trait", a struct you can specialize and draw the true return type from:
// in the normal case, just the identity
template<class T>
struct item_return{ typedef T type; };
template<class T>
typename item_return<T>::type item();
template<>
struct item_return<float>{ typedef int type; };
template<>
int item<float>();
現(xiàn)場(chǎng)示例.
請(qǐng)注意,您可能希望遵循以下規(guī)則,因此您只需更新 item_return
專業(yè)化中的 return-type.
Note that you might want to stick to the following, so you only need to update the return-type in the item_return
specialization.
template<>
item_return<float>::type foo<float>(){ ... }
// note: No `typename` needed, because `float` is not a dependent type
這篇關(guān)于在函數(shù)模板特化中覆蓋返回類型的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!