简体   繁体   中英

Could not convert from '<brace-enclosed initializer list> to

I know that has a lot of questions similar, but I saw them and none of them helped me, I think is that because mine is kind of different, and at the same time weird.

I made another question and a member answered to me, but instead of using classes he used structs. and it's working perfectly, but when I try to put it as classes, using the same logic, this is what happen, the error:

error: could not convert '{{"foo", "bar"}}' from '' to 'B'

I tried, but I don't know what is happening.

#include <iostream>
#include <map>

class A
{
public:
    A() {}
    A(const std::string & input) : data(input) {}
private:
    std::string data;
};

class B
{
public:
    B();
    B(std::initializer_list<std::pair<std::string, A>> input) : container(begin(input), end(input)) {}
private:
    std::map<std::string, A> container;
};

int main( int argc, char ** argv )
{
    B b = {
        {"foo", "bar"}
    };

    return 0;
}

Also the answer of the member here: Ideone

Thank you all.

You must initialize the 'b' like this:

B b = {
    { "foo", A{"bar"} }
};

Because {"foo", "bar"} is of type {string, string} instead of {string, A}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM