Search code examples
c++classc++11templatesreturn-type

How to get resultant type of multiplying two different types?


How would one go about getting the resultant type of multiplying two different types i.e.

template< typename TA, typename TB>
struct multiplier
{
    using result_type = // something here finds result of TA * TB
    result_type operator()( TA a, TB b ) const
    {
        return a * b;
    }
};

I know in C++ it is perfectly valid to multiply two numerical values of different type and this will give a value in a type that is known to the compiler. I.e. multiplying a double and an int will result in a double type answer.

As such in a template class where the types are known at compile-time, it should be possible to determine the type that will be created. Indeed a lambda can be created to return the result of this value i.e.

auto foo = [](int a, float b){ return a * b;}
auto c = foo( 13, 42.0 );

This would cause c to be a float.

Please note, that I am limited to being able to use only features of or below.


Solution

  • You can use decltype to do this:

    using result_type = decltype(std::declval<TA&>() * std::declval<TB&>());