Why I can use const char* as key in std::map<std::string, int>

c++, type-conversion

Solution

`std::string` has a constructor that allows the implicit conversion from `const char*`.

basic_string( const CharT* s,
              const Allocator& alloc = Allocator() );

means that an implicit conversion such as

std::string s = "Hello";

is allowed.

It is the equivalent of doing something like

struct Foo
{
  Foo() {}
  Foo(int) {} // implicit converting constructor.
};

Foo f1 = 42;
Foo f2;
f2 = 33 + 9;

If you wanted to disallow the implicit conversion construction, you mark the constructor as `explicit`:

struct Foo 
{
  explicit Foo(int) {}
};

Foo f = 33+9; // error
Foo f(33+9); // OK
f = Foo(33+9); // OK

Problem

I have define a data structure ``` std::map<std::string, int> a; ``` I found I can pass const char* as key, like this: ``` a["abc"] = 1; ``` Which function provides automatic type conversion from const char* to std::string?

Original source