为什么未调用自由函数作为构造函数中的参数传递
Why a free function passed as a parameter in the constructor is not called?
为什么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
的新标识符。
相关文章:
- 在执行new期间是否可以在构造函数中传递不同的参数?
- shared_ptr构造函数参数是否应按值传递
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 将派生类构造函数参数传递给受保护的成员
- 在构造函数上传递参数或在每个方法上传递参数
- 如何将变量作为构造函数参数或函数参数传递
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 示例自定义共享_ptr-我如何传递构造函数参数 - 我在此处使用variadic模板
- 引用成员到构造函数参数按值传递
- C++将Lambda函数作为类构造函数参数传递
- C :在构造函数中传递指针类参数
- c++在创建时将构造函数参数从父对象传递到子对象
- 在具有boost工厂的构造函数中传递参数
- 在构造函数中传递枚举作为参数
- 将字符串构造作为函数参数传递
- 将构造函数参数传递给模板函数工厂
- 如何删除在 c++ 中作为构造函数参数传递的已分配变量
- 不能正确识别作为构造函数参数传递的函数
- 将方法作为构造函数参数传递
- 为每个可变模板参数调用函数,并将结果作为构造函数参数传递