Declaring Compile-Time Strings Concisley in C
Introduction
In C , declaring compile-time strings, which remain constant throughout compilation, can prove cumbersome. Traditional approaches require specifying a variadic sequence of characters:
using str = sequence<'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!'>;
Existing Approaches: Challenges and Limitations
Ideally, declaring compile-time strings should be more straightforward, such as:
using str1 = sequence<"Hello, world!">; constexpr auto str2 = "Hello, world!"_s;
However, these approaches face obstacles:
Solution: str_const Library
As of Scott Schurr's presentation at C Now 2012, the str_const library offers a convenient solution:
constexpr str_const my_string = "Hello, world!"; static_assert(my_string.size() == 13); static_assert(my_string[4] == 'o'); constexpr str_const world(my_string, 7, 5); static_assert(world == "world");
This solution provides benefits such as constexpr range checking and flexible substring retrieval, without the need for macros.
Update: C 17 and std::string_view
In C 17, std::string_view offers a similar solution:
constexpr std::string_view my_string = "Hello, world!"; static_assert(my_string.size() == 13); static_assert(my_string[4] == 'o'); constexpr std::string_view world(my_string.substr(7, 5)); static_assert(world == "world");
This approach provides the following advantages:
The above is the detailed content of How Can I Concisely Declare Compile-Time Strings in C ?. For more information, please follow other related articles on the PHP Chinese website!