Why doesn't a function prevent a construct from another type of return?

std::function allows you to do this:

 std::function<void()> = []()->int{return 42;}; 

But not this:

 std::function<void()> = [](int i)->int{return 42;}; 

Presumably because the return type is not part of the function signature. But std::function is the type of the class that is given the type of the return value and it knows the type of the return object of the function from which it built. So there is a compiler error here.

Why is there no compiler error?

+5
source share
1 answer

An error occurred in the C ++ 11 standard that made everything std::function<void(???)> completely unusable. Some compilers interpreted an error meaning that the return type of something stored in such a std::function should be ignored, others that only void were compatible with such a std::function .

In defect resolution (via @tc), it was fixed, so std::function<void(???)> ignores the return type (and value) of the stored object.

Your compiler uses this interpretation, which is current.

Regardless, the arguments must be converted from the arguments to std::function .

In short, so says the standard (revised).

In practice, it is useful to discard the return values. Average time, you cannot call a function or called object without data to call it. It was decided that an imperfect match is in order (so if the arguments / return values ​​are converted, std::function is a game). And there you have it.

+4
source

All Articles