覆盖函数模板专用化中的返回类型 [英] Overriding return type in function template specialization
本文介绍了覆盖函数模板专用化中的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想专门化一个函数模板,使得返回类型根据模板参数的类型而改变。
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.
推荐答案
由于专业化必须与返回类型上的基本模板一致,你可以通过添加一个返回类型trait,一个结构你可以专门化,并绘制真正的返回类型从:
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>();
Live example.
请注意,您可能需要遵循以下内容,因此您只需要更新 item_return
专业化。
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
这篇关于覆盖函数模板专用化中的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文