Home > Enterprise >  how to deduce function template argument from function return type?
how to deduce function template argument from function return type?

Time:01-09

Example:

template<typename T>
T get() {
    return T{};
}

void test() {
    float f = get();//requires template argument; e.g. get<float>();
}

I understand that float can be converted to double or even int; is it possible to have get<T> instanciated automatically based on the requested return type? If so how?

CodePudding user response:

No, template argument deduction from the return type works only for conversion operator templates:

struct A {
    template<typename T>
    operator T() {
        //...
    }
};

//...

// calls `operator T()` with `T == float` to convert the `A` temporary to `float`
float f = A{};

This can also be used to have get return the A object so that float f = get(); syntax will work as well. However, it is questionable whether using this mechanism as you intent is a good idea. There are quite a few caveats and can easily become difficult to follow. For example what happens in auto f = get();? What happens if there are multiple overloads of a function g in a call g(get())? Etc.

Instead move your type specifier to the template argument and you wont have to repeat yourself:

auto f = get<float>();
  • Related