【问题标题】:Use a function's return type as for another template function call使用函数的返回类型作为另一个模板函数调用
【发布时间】:2015-05-29 18:31:04
【问题描述】:

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

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

【问题讨论】:

  • 你有多个模板化的 transformValue 函数还是什么?
  • @MarcoA.:是的,transformValue 也是模板化的。
  • 函数不能自然派生模板类型吗?通常你不应该为函数指定模板参数,而是让模板参数推导为你工作。
  • @NathanOliver:我不得不改变一些东西,而推论确实奏效了!谢谢。

标签: c++ templates c++03


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-08-05
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    相关资源
    最近更新 更多