0

The following code fails to compile.

#include <iostream>
#include <map>
#include <vector>

using namespace std;

class mc
{
    string s;
    public:
    mc(const std::string s) : s{s}{};
    // mc(const char * s) : s{s}{}; // Adding this line would make it work in both cases
};


int main()
{
    vector<mc> a = {"Hello", "there"};          //FAILS
    vector<mc> b = {mc("Hello"), mc("there")};  //WORKS
}

Depending on compiler error is

no matching function for call to  mc::mc(const char&)
note: candidate: ‘mc::mc(std::string)’
note: no known conversion for argument 1 from ‘const char’ to ‘std::string’

or

/usr/include/c++/11/bits/stl_uninitialized.h:138:72: error: static assertion failed: result type must be constructible from value type of input range

Why does this error happen? There is an implicit constructor from string. If instead of vector<mc> they were vector<string> it would work.

15
  • What is SatId (from your error)? Commented Mar 3, 2023 at 13:47
  • 3
    The compiler will only do 1 user-defined conversion in a conversion sequence. The code above requires 2 from char const * -> std::string -> mc Commented Mar 3, 2023 at 13:52
  • Note that mc a = "Hello"; also fails. Commented Mar 3, 2023 at 13:54
  • only one implicit user-defined conversion is allowed. Commented Mar 3, 2023 at 14:01
  • This case is not about two implicit user-defined conversions, but about why the initialization of a std::vector from a range given by two iterators (constructor #5) does not work. Commented Mar 6, 2023 at 9:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.