在函数模板特化中覆盖返回类型 [英] Overriding return type in function template specialization

查看:26
本文介绍了在函数模板特化中覆盖返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于在函数模板特化中覆盖返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆