Std :: result_of for inline statements

What is the correct syntax for determining the result of something like -int() or double()*double() via result_of ?

This does not work

 std::result_of<operator-(int)>::type std::result_of<operator*(double,double)>::type 
+6
source share
2 answers

std::result_of is actually not the approach you need to take here. decltype does exactly what you want and can be used as decltype(-int()) , decltype(double()*double()) , etc. If you don't know if the type is constructive by default, you can also use std::declval : decltype(-std::declval<int>()) .

The reason that any syntax including operator- will not work, because the operator- syntax works only for user overloaded operators. Built-in operators have no support function that can be referenced.

+8
source

decltype is definitely the way to go, but if you must use result_of , you can do this using function objects defined in <functional>

For example, to get the resulting type double * double , use

 std::result_of<std::multiplies<double>(double, double)>::type 

Similarly, unary negation would be

 std::result_of<std::negate<int>(int)>::type 

With C ++ 14, you can even query the resulting type of mathematical operation on two different types

 std::result_of<std::plus<>(double, int)>::type 

Of course, the same method can be used for custom types.

 struct foo{}; struct bar{}; bar operator/(foo, foo) { return bar{}; } std::result_of<std::divides<>(foo, foo)>::type 

Live demo

+3
source

Source: https://habr.com/ru/post/979723/


All Articles