Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 c++11 or below.

like image 519
lmcdowall Avatar asked Aug 12 '19 15:08

lmcdowall


2 Answers

In addition to the other answers, if you do not need the result_type for later use, but only to specify the return type of the operator(), there is another way, by not defining the alias for result_type in c++11.

You can provide a trailing return type along with auto return as follows:

template< typename TA, typename TB>
struct multiplier
{
    auto operator()(TA a, TB b) const -> decltype(a * b)
//  ^^^^^                             ^^^^^^^^^^^^^^^^^^^
    {
        return a * b;
    }
};

(See live online)

like image 71
JeJo Avatar answered Sep 19 '22 16:09

JeJo


You can use decltype to do this:

using result_type = decltype(std::declval<TA&>() * std::declval<TB&>());
like image 30
Jeremy Roman Avatar answered Sep 22 '22 16:09

Jeremy Roman