Why and how is std::function<void()> allowed to be assigned to callables with return types in C++?
The following code is legal C++:
int m() { return 42; }
int main() {
std::function<void()> func, func2;
func = m;
func2 = [&]() -> std::string { return "This does not return void"; };
}
By passing void()
to std::function
's template argument list, I assumed that meant func
and func2
must be assigned to functio开发者_如何学编程ns/lambdas that return nothing. That is clearly not true.
Firstly, why is std::function
designed to do this? This seems really surprising to me.
Secondly, how did they design std::function
this way? I know std::function
uses type erasure to be assignable to different types of callables, but since we explicitly supplied void()
, shouldn't the different callables assigned to func
and func2
- whether they are lambdas or functions - only be returning void
?
It behaves like
class function {
public:
void operator() {
m();
}
};
If you want to get errors, declare them like
std::function<void*()> func, func2;
精彩评论