c++ - Ambiguous constructor between list<string> and string -
in following code, compiler gives me error when try pass list constructor:
#include <string> #include <iostream> #include <list> class myclass { std::list<std::string> strings; public: void disp() { (auto &str : strings) std::cout << str << std::endl; } myclass(std::string const &str) : strings({str}) {} myclass(std::list<std::string> const &strlist) : strings(strlist) {} }; int main () { // compiles well: myclass c1("azerty"); c1.disp(); // compilation error, "call constructor of 'myclass' ambiguous": myclass c2({"azerty", "qwerty"}); c2.disp(); return 0; }
i tried add explicit
constructors' declarations, doesn't change anything.
the problem string
has constructor:
template< class inputit > basic_string( inputit first, inputit last, const allocator& alloc = allocator() );
which {"azerty", "qwerty"}
unfortunate match because const char*
is, in fact, input iterator... if 2 arguments aren't intended iterators , aren't iterators same container.
one solution provide single constructor takes initializer list , use one:
myclass(std::initializer_list<std::string> il) : strings(il.begin(), il.end()) { }
Comments
Post a Comment