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 determine function output type based on template parameters?

The following construct is a minimal example of what I try to achieve: let the return type of a templated function depend on the input types. First I wrote (below a selection of a set that also specializes for std::complex<> variants):

template<class U, class V> struct result_type                { using type = U; };
template<>                 struct result_type<float, double> { using type = double; };
template<>                 struct result_type<double, float> { using type = double; };

Normally you could somewhere use in code:

template<typename U, typename V>
void function()
{ 
    using R = typename result_type<U, V>::type;
    ...
}

But in my case I need the construct:

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

template<typename U, typename V>
R function()  // Determine 'R' by result_type<U, V>::type
{         
    ...
}

I cannot find the right code to do this. Can this be done anyway?

>Solution :

This is one way to use your type trait to define the return type of the function:

template<typename U, typename V>
typename result_type<U, V>::type function()
{         
    // return {}; // ...
}

A possible simplification could be to make use of std::common_type:

template<typename U, typename V>
std::common_type_t<U, V> function() {
    // return {}; // ...
}
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