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

时间:2017-09-12 15:58:07

标签: c++ function c++11 lambda constructor

为什么mystruct( plain_old_function );构造函数不调用默认构造函数而lambda调用专用元素(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;
}

Demo

输出:

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

2 个答案:

答案 0 :(得分:7)

Vexing解析,

mystruct( free_function );

被解析为

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

您可以使用{}

mystruct{free_function};

答案 1 :(得分:0)

虽然您绝对应该更喜欢大括号初始化,但在这种情况下,您可以通过进行限定查找而不是非限定名称查找来避免烦恼的解析:

mystruct( ::free_function );

无法解决引入名为free_function

的新标识符的问题