Given the following code:
#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";
}
This code works. But if I uncomment the commented-out line - which is trying to initialise a info
struct in the same way that the std::pair is initialsing then it fails. I can't figure out why...
The error get is:
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();} };
^
Link to my test code: here (wandbox)
The problem here is
std::string name {""};
You use a in class member initializer, and in C++11, that is not allowed if you want the object to be an aggregate (per [dcl.init.aggr]/1). To get this to compile in C++11 you have to remove it.
In C++14 and above that constraint was removed (updated [dcl.init.aggr]/1) and in class member initializers are allowed in aggregates and the code will compile as is.