在函数模板特化中覆盖返回类型

2021-12-13 00:00:00 templates c++

我想专门化一个函数模板,以便返回类型根据模板参数的类型而变化.

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.

推荐答案

由于专业化必须与返回类型的基本模板一致,您可以通过添加返回类型特征"来实现,您可以使用一个结构专门化并从以下位置绘制真正的返回类型:

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>();

现场示例.

请注意,您可能希望遵循以下规则,因此您只需更新 item_return 专业化中的 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

相关文章