c++ 03中模板函数返回类型的推导
Template function return type deduction in C++03
我想在c++ 03中实现以下内容:
template <typename T1, typename T2>
T1 convert(bool condition, T2& value)
{
return condition ? value : conversionFunction(value);
}
除非我想调用convert
,而不必显式指定T1
。我怎么做呢?
也许你可以使用一个hack。窍门是推迟转换,直到实际使用返回值。返回值是一个helper对象,允许将其自身转换为其他内容。
template <typename T>
struct ConvertHack {
T &value_;
const bool cond_;
ConvertHack (bool cond, T &value) : value_(value), cond_(cond) {}
template <typename U> operator U () const {
return cond_ ? value_ : conversionFunction(value_);
}
};
template <typename T>
ConvertHack<T> convert(bool condition, T& value) {
return ConvertHack<T>(condition, value);
}
返回类型不会被编译器推断出来(这与返回类型不支持重载是一致的)。你必须显式地指定这个模板参数,例如通过调用
convert<Obj>(x);
第二个模板形参不需要指定,即使第一个模板形参已经被显式指定,它也可以被推导出来(所以总是把需要显式指定的模板形参放在可以推导出来的形参之前!)
但是,只有当conversionFunction
和T2&
的返回类型都可以转换为T1
时才有效;因为编译器不能知道condition
在运行时的值是多少,所以它必须确保?:
的两个"分支"都是可编译的。在这种情况下,使用typename boost::common_type<T1, ReturnTypeOfConversionFunction>::type
作为返回值。如果不能很容易地确定ReturnTypeOfConversionFunction
,可以使用Boost.TypeOf.
如果条件可以在编译时求值,并且只依赖于T2
,则可以使用模板元编程:
template <bool condition, typename T2>
struct Converter;
template<typename T2>
struct Converter<true, T2> { // If the condition is true, use this.
typedef T2 type;
static type doConvert(T2& value) { return value; }
};
template<typename T2>
struct Converter<false, T2> { // If the condition is false, use this.
typedef ReturnTypeOfConversionFunction type;
static type doConvert(T2& value) { return conversionFunction(value); }
};
template <typename T2>
typename Converter</* condition */, ReturnTypeOfConversionFunction>::type
convert(T2& value)
{
return Converter<condition, T2, ReturnTypeOfConversionFunction>::doConvert(value);
}
代替/* condition*/
, Boost中的类型特征可能会有帮助。
用于Converter
的语法称为部分模板专门化。在指定convert
的返回值时,为什么需要typename
,请参阅此处。
相关文章:
- 如何获取std::result_of函数的返回类型
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 函数作为模板参数,是否对返回类型强制约束
- C++中函数的向量返回类型引发错误
- 检查函数返回类型是否与STL容器类型值相同
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 在 c++ 中将函数返回类型指定为模板参数
- 使用 SWIG 更改生成的 CS 函数中的返回类型
- C++ 这里有一个返回 (24) 的布尔返回类型函数
- 使用SFINAE来检测void返回类型函数的存在
- 模板返回类型函数如何在C++中工作
- 如何在返回类型函数模板的专用化中使用派生类型?( "couldn't infer template argument" )
- Bon appetit :从 int 返回类型函数在 main() 中打印字符串
- 在引用或指针返回类型函数上输入
- 在后面的返回类型函数语法中,auto关键字背后是否有意图
- 我可以在c++中重写字符串返回类型函数吗?