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}
Related videos on Youtube
Author by
SH.0x90
Updated on June 04, 2022Comments
-
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 about 10 yearsA string literal to an
A
is two user-defined conversions, so that's not going to work implicitly. -
SH.0x90 about 10 yearsYes, 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 about 10 yearsYou could make an overload of
A
's constructor that takes aconst char *
and delegates to the other one. -
Adam H. Peterson about 10 yearsThe only difference between
struct
andclass
is default access:public
versusprivate
. (In fact, the only time I ever use theclass
keyword anymore is with template-template parameters.) Do you mean aggregate versus non-aggregate? -
SH.0x90 about 10 yearsI 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 about 10 yearsYou can get the same encapsulation with
struct
you can withclass
. If the first thing you're going to do is putpublic:
at the top, there's not really any effective difference.
-