Anycorn
Anycorn

Reputation: 51565

std::result_of for built-in operators

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

This fails

std::result_of<operator-(int)>::type
std::result_of<operator*(double,double)>::type

Upvotes: 6

Views: 749

Answers (2)

Praetorian
Praetorian

Reputation: 109289

decltype is definitely the way to go here, but if you must use result_of, it can be done by using the function objects defined in <functional>

For instance, to get the resulting type of 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 a mathematical operation on two different types

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

Of course, this same technique can be used for user defined types as well

struct foo{};
struct bar{};
bar operator/(foo, foo) { return bar{}; }

std::result_of<std::divides<>(foo, foo)>::type

Live demo

Upvotes: 3

user743382
user743382

Reputation:

std::result_of is really not the approach 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 default-constructible, you can also use std::declval: decltype(-std::declval<int>()).

The reason any syntax involving operator- won't work is because the operator- syntax only works for custom overloaded operators. Built-in operators don't have any backing function that can be referred to.

Upvotes: 8

Related Questions