Conveniently Declaring Compile-Time Strings in C++

I haven’t seen anything to match the elegance of Scott Schurr’s str_const presented at C++ Now 2012. It does require constexpr though.

Here’s how you can use it, and what it can do:

    constexpr str_const my_string = "Hello, world!";
    static_assert(my_string.size() == 13, "");
    static_assert(my_string[4] == 'o', "");
    constexpr str_const my_other_string = my_string;
    static_assert(my_string == my_other_string, "");
    constexpr str_const world(my_string, 7, 5);
    static_assert(world == "world", "");
//  constexpr char x = world[5]; // Does not compile because index is out of range!

It doesn’t get much cooler than compile-time range checking!

Both the use, and the implementation, is free of macros. And there is no artificial limit on string size. I’d post the implementation here, but I’m respecting Scott’s implicit copyright. The implementation is on a single slide of his presentation linked to above.

Update C++17

In the years since I posted this answer, std::string_view has become part of our tool chest. Here is how I would rewrite the above using string_view:

#include <string_view>

    constexpr std::string_view my_string = "Hello, world!";
    static_assert(my_string.size() == 13);
    static_assert(my_string[4] == 'o');
    constexpr std::string_view my_other_string = my_string;
    static_assert(my_string == my_other_string);
    constexpr std::string_view world(my_string.substr(7, 5));
    static_assert(world == "world");
//  constexpr char x =; // Does not compile because index is out of range!

Leave a Comment