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.
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)
You can use decltype
to do this:
using result_type = decltype(std::declval<TA&>() * std::declval<TB&>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With