Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to deduce function template argument from function return type?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading