Search code examples
c++c++11constexprauto

What type does static auto constexpr t = {"red", "black", "green"}; derive to?


So I was messing around with some code and I decided that I wanted some sort of list of strings... so then I thought - I can't be bothered to figure out what types to use and so on, so I would just whack it into an auto variable, like this:

static auto constexpr t = {"red", "black", "green"};

and the code compiled. Great, so since this:

static auto constexpr str = "green";

derives to a char[] I was assuming that {"red", "black", "green"} might be a *char[] or some such, thus I could write:

std::cout << "value 1 is: " << t[1] << std::endl;

Which gives me the error:

main.cpp:18:56: error: no match for ‘operator[]’ (operand types are ‘const std::initializer_list’ and ‘int’)

So I presume the type is "initializer_list"? Is there a way I can do somthing like: t[1] to get at the string "black" (assuming index starts at 0)?


Solution

  • So I presume the type is "initializer_list"?

    Yes.

    Is there a way I can do somthing like: t[1] to get at the string "black" (assuming index starts at 0)?

    Use std::array, which plays nicely with C++17 class template type deduction:

    static auto constexpr t = std::array{"red", "black", "green"};
    
    std::cout << t[1] << "\n"; // outputs 'black'
    

    constexpr-ness is preserved if you pass compile time constants to operator[] or std::get.

    constexpr const char* black = t[1];
    constexpr const char* red = std::get<0>(t);