简体   繁体   中英

Use a function's return type as for another template function call

I'd like call a templated function with the typename being determined by another function's return type:

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

EDIT: I cannot use C++11 :(

In your specific case you'd better just rely on template type deduction instead of specifying it explicitly

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM