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

10,710

You must initialize the 'b' like this:

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

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

Share:
10,710

Related videos on Youtube

SH.0x90
Author by

SH.0x90

Updated on June 04, 2022

Comments

  • SH.0x90
    SH.0x90 almost 2 years

    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 '<brace-enclosed initializer list>' 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.

    • chris
      chris about 10 years
      A string literal to an A is two user-defined conversions, so that's not going to work implicitly.
    • SH.0x90
      SH.0x90 about 10 years
      Yes, you are right, I just tried this removing the "bar" and putting std::string("bar") and it worked. Do you have a solution to this work in both ways?
    • chris
      chris about 10 years
      You could make an overload of A's constructor that takes a const char * and delegates to the other one.
    • Adam H. Peterson
      Adam H. Peterson about 10 years
      The only difference between struct and class is default access: public versus private. (In fact, the only time I ever use the class keyword anymore is with template-template parameters.) Do you mean aggregate versus non-aggregate?
    • SH.0x90
      SH.0x90 about 10 years
      I prefer to use classes sometimes because of the encapsulation, and it's a thing that I REALLY care about. Nut there are situations that you can use for sure the structs without concern.
    • Adam H. Peterson
      Adam H. Peterson about 10 years
      You can get the same encapsulation with struct you can with class. If the first thing you're going to do is put public: at the top, there's not really any effective difference.