c++ - Why a free function passed as a parameter in the constructor is not called? -


why doesn't mystruct( plain_old_function ); constructor calls default constructor while same lambda calls specialized 1 (mystruct ( const std::function< std::string() > &func ))?

can made work?

#include <iostream> #include <functional> #include <string>  struct mystruct {     mystruct() { std::cout << "default construct :s" << std::endl; }     mystruct ( const std::function< std::string() > &func )  {         std::cout << func() << std::endl;     } };  void callme ( const std::function< std::string() > &func ) {     std::cout << func() << std::endl; }  std::string free_function(  ) {  return "* free function"; }   int main() {      std::cout << "constructing lambda:" << std::endl;     mystruct( [](){ return "* lambda function"; } );      std::cout << "calling free  function through function:" << std::endl;     callme( free_function );      std::cout << "constructing free function:" << std::endl;     mystruct( free_function );      return 0; } 

demo

output:

constructing lambda: * lambda function calling free  function through function: * free function constructing free function: default construct :s 

vexing parse,

mystruct( free_function ); 

is parsed as

mystruct free_function; // declare mystruct instance named free_function                         // (hiding function) 

you may use {}:

mystruct{free_function}; 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -