Search code examples
c++c++17template-argument-deduction

Why can't a string literal initializer list for a std::vector create a std::vector<std::string> in C++?


In C++, if I do:

std::vector words {"some","test","cases","here"};
  • Can anyone explain why words is not a std::vector<std::string> type of container?

  • Isn't C++ supposed to deduct the type through the initializer-list I gave?

  • If "some", "test" are not string literals, what do std::string literals look like?


Solution

  • a string literal, like "something", is a c-string. It creates a const char[N] with static storage duration where N is the number of characters plus a null terminator. That means when you do

    std::vector words {"some","test","cases","here"};
    

    What you've done is create a std::vector<const char*> since arrays can decay to pointers.

    If you want a std::vector<std::string> then what you need is to use the std::string user defined literal. That would look like

    using namespace std::string_literals;
    std::vector words {"some"s,"test"s,"cases"s,"here"s};
    

    and now you have actually std::strings that the compiler will use to deduce the type of the vector.