static_assert doesn't work as expected when using std::is_same, std::result_of and std::bind

853 views Asked by At

I'm experiencing a weird behavior when using static_assert for asserting that the return type of a function object is the same as another type. Something like (This code is just for presenting the problem and not actually what i'm trying to do).

int foo() {
    return 0;
}

int main() {
    auto funcObj = std::bind(foo);
    static_assert(std::is_same<std::result_of<funcObj()>, int>::value, "FuncObj return type is not int");
    return 0;
}

The assertion fails. What's going wrong here?

2

There are 2 answers

0
Yakk - Adam Nevraumont On

std::result_of<?> is a useless type to use directly.

typename std::result_of<?>::type and std::result_of_t<?> (in C++14) what you want.

An easy way to get a good error message for this kind of thing is:

std::result_of<decltype(funcObj)()> x = 3;

which should generate error messages that make it clear that the lhs type is not int like you expected. (cannot convert int to 'some complex type' usually).

0
R Sahu On

The line

static_assert(std::is_same<std::result_of<funcObj()>, int>::value, "FuncObj return type is not int");

needs to be

static_assert(std::is_same<typename std::result_of<decltype(funcObj)()>::type, int>::value, "FuncObj return type is not int");
        // Missing pieces  ^^^^^^^^                                 ^^ ^^^^^^