给定以下代码:
#include <functional>
#include <string>
#include <iostream>
class test
{
public:
struct info
{
std::string name {""};
std::function<bool()> func;
};
//info my_info { "test_name", [&]{return member_func();} }; // <------ ERROR HERE
std::pair<std::string, std::function<bool()>> my_info_pair { "test_name", [&]{return member_func();} };
bool member_func()
{
std::cout << "member_func\n";
return true;
};
};
int main() {
std::cout << "start\n";
test t;
std::cout << t.my_info_pair.first << std::endl;
t.my_info_pair.second();
std::cout << "end\n";
}
此代码有效。但是,如果我取消注释已注释掉的行——它试图以info
与 std::pair 初始化相同的方式初始化一个结构,那么它就会失败。我想不通为什么...
得到的错误是:
prog.cc:15:60: error: could not convert '{"test_name", <lambda closure
object>test::<lambda()>{((test*)this)}}' from '<brace-enclosed
initializer list>' to 'test::info'
info my_info { "test_name", [&]{return member_func();} };
^
链接到我的测试代码:这里(魔杖盒)