为什么未调用自由函数作为构造函数中的参数传递

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

本文关键字:构造函数 参数传递 调用 自由 函数 为什么      更新时间:2023-10-16

为什么mystruct( plain_old_function );构造函数不调用默认构造函数,而lambda则调用专用One(mystruct ( const std::function< std::string() > &func ))?

可以做到这一点吗?

#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;
}

演示

输出:

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

vexing parse,

mystruct( free_function );

被解析为

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

您可以使用{}

mystruct{free_function};

虽然您绝对喜欢支撑初始化,但在这种情况下,您可以通过进行合格的查找而不是不合格的名称查找来避免其他方式来避免其他方式:

mystruct( ::free_function );

这不能解决,以引入名为free_function的新标识符。