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

标签 c++ templates c++03

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

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 :(

最佳答案

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

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

关于c++ - 使用函数的返回类型作为另一个模板函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30536672/

相关文章:

c++ - 使用 c++0x 标志编译 wxWidgets

c++ - 在 C++11 之前的版本中将字符串列表填充到 vector 中

c++ - 在一个纹理中读取和写入 (OpenGL)

c++ - 无法将参数 1 从 'VP<T>' 转换为 'VP<T> &' ,又一个 VS bug

python - 如何在 django 模板中运行此代码

c++ - 通用设计混合了奇怪的重复模板模式。 C++

c++ - 使用 boost::bind 但允许传递任何附加参数

c++ - 在没有 C++11 的情况下用 C++ 进行回调的最干净的方法?

c++ - 使用 -l 混淆在 G++ 中包含库

c++ - 在 C++ 中计算标准差和方差