Search code examples
c++arrayscompilationc++20

How to verify a std::array size during compile time?


I defined a static constexpr std::array with string views like:

 constexpr int array_size = 6;
 static constexpr std::array<std::string_view, array_size> texts = {{"one", "two", "three"}};

During compilation, I want to check whether the size of the array (array_size) corresponds with the number of items in the array (which can be checked if the string_view is "" or filled). How to do this during compile time and show an error to the user if strings are missing in the texts array? Is this possible with a static_assert or are there other ways to achieve this in C++20?


Solution

  • You can use std::to_array() to specify only the element type, and have the size deduced. Then you can verify the size with a static_assert:

    constexpr auto texts = std::to_array<std::string_view>({
        "one",
        "two",
        "three"
    });
    
    static_assert(texts.size() == 3);
    

    Also, if you don't need to override the element type, you can do this instead:

    constexpr std::array texts = {"one", "two", "three"};
    static_assert(texts.size() == 3);
    

    In this case it will result in const char * being used as the element type.