gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:09:28 26 4
gpt4 key购买 nike

为什么 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

最佳答案

烦人的解析,

mystruct( free_function );

被解析为

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

您可以使用 {}:

mystruct{free_function};

关于c++ - 为什么不调用在构造函数中作为参数传递的自由函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46180907/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com