使用函数的返回类型作为另一个模板函数调用

时间:2015-05-29 18:31:05

标签: c++ templates c++03

我想调用一个模板化函数,其typename由另一个函数的返回类型决定:

template<typename T>
void doSomething(T& value, int x)
{
    if(getResult(x)) // Continue as normal if the result is true.
    {   
        object.call<T>(value, x);
    }
    else
    {
        //I'd like to have this function be templated on the
        //return type of the transformValue function. This
        //transformValue functions takes in a value of some type
        //and then transforms it to some value of other type.
        object.call<return_type_of_transform_value>(transformValue(value), x);
    }
}

// Some condition
bool getResult(int x)
{
    if(x == 42)
    {
        return true;
    }
    else
    {
        return false;
    }
}

编辑:我不能使用C ++ 11 :(

1 个答案:

答案 0 :(得分:3)

在您的具体情况下,您最好只依靠模板类型扣除而不是明确指定

class Object { // Sample object
public:
  template<typename T>
  void call(T whatever, int x) { // Sample templated function (you didn't provide the code)
      std::cout << "called call";
  }
};

template<typename T>
void doSomething(T& value, int x)
{

    Object obj;
    if(getResult(x))
    {   //Continue as normal if the result is true.
        obj.call<T>(value, x);
    }

    else
    {   
        obj.call(transformValue(value), x); // Type deduction
    }
}

Live Example