Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 functions/lambdas that return nothing. That is clearly not true.

Firstly, why is std::function designed to do this? This seems really surprising to me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

It behaves like

class function {
 public:
  void operator() {
    m();
  }
};

If you want to get errors, declare them like

std::function<void*()> func, func2;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading