mercredi 27 mars 2019

c++11 struggling to understand why I can't uniform init a structure, but I can init a std::pair of similar type

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)

Aucun commentaire:

Enregistrer un commentaire