C ++ 03中的模板函数返回类型推导

时间:2015-05-29 20:17:13

标签: c++ templates template-deduction return-type-deduction

我想在C ++ 03中实现以下内容:

template <typename T1, typename T2>
T1 convert(bool condition, T2& value)
{
    return condition ? value : conversionFunction(value);
}

除非我想在不必明确指定convert的情况下致电T1。我怎么做?

2 个答案:

答案 0 :(得分:2)

也许你可以使用黑客攻击。黑客是推迟转换,直到您实际使用返回值。返回值是一个辅助对象,它允许自己转换为其他东西。

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

答案 1 :(得分:0)

编译器不推断返回类型(这与返回类型不支持的重载一致)。您必须明确指定此模板参数,例如通过调用

convert<Obj>(x);

不必指定第二个模板参数,即使已明确指定了第一个模板参数,也可以推导出它(因此,总是将模板参数放在需要明确指定的模板参数之前!)。

但是,只有当conversionFunctionT2&的返回类型都可以转换为T1时才有效;由于编译器无法知道condition在运行时具有什么值,因此必须确保两个&#34;分支&#34; ?:的可编译。在这种情况下,请使用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*/type traits from Boost可能会有所帮助。

Converter使用的语法称为部分template specialization。 有关typename的返回值时需要convert的原因,请参阅here