Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't function prevent construction from different return type?

Tags:

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 a function's signature. But std::function is a class type that is given a return type and knows the return type of the function object it's constructed from. So there's a possibility of a compiler error here.

Why is there no compiler error?

like image 246
user6428127 Avatar asked Jun 05 '16 23:06

user6428127


1 Answers

There was a bug in the C++11 standard that made all std::function<void(???)> completely unusable. Some compilers interpreted the bug to mean the return type of anything stored in such a std::function should be ignored, others that only void was compatible with such a std::function.

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

Your compiler is using that interpretation, which is the current one.

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

In short, because the standard (revised) says so.

In practice, being able to discard return values is useful. Mean while, you cannot invoke a function or callable object without data to invoke it. It was decided that imperfect matching is ok (so if the arguments/return values convert, std::function is game). And there you have it.

like image 114
Yakk - Adam Nevraumont Avatar answered Sep 28 '22 05:09

Yakk - Adam Nevraumont