也许你可以使用下面的技巧。鉴于这些简单的类型特点:
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