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

Viewed 85

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

Can this be made to 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 with lambda:" << std::endl;
    mystruct( [](){ return "* Lambda function"; } );

    std::cout << "Calling free  function through another function:" << std::endl;
    callme( free_function );

    std::cout << "Constructing with free function:" << std::endl;
    mystruct( free_function );

    return 0;
}

Demo

Output:

Constructing with lambda:
* Lambda function
Calling free  function through another function:
* Free function
Constructing with free function:
Default construct :S
2 Answers
Related