I've got a class that has a bunch of constant strings, in the form of:
using namespace std::string_view_literals;
class T {
static const constexpr std::string_view something1 = "Alice"sv;
static const constexpr std::string_view something2 = "Bob"sv;
static const constexpr std::string_view something3 = "Charlie"sv;
...
};
I'm currently using
the string_view_literals
namespace, but this isn't good practice in a header file, and generates warnings:
Using namespace directive in global context in header [-Wheader-hygiene]
(clang)
literal operator suffixes not preceded by '_' are reserved for future standardization [-Wliteral-suffix]
(gcc7)
I'd like to look at other options.
Ignore the warnings
Directly import the one literal I'm using, instead of the whole namespace
using std::string_view_literals::operator""sv
Since this is a constexpr constant, perhaps I should just call the constructor directly, knowing it has no runtime memory or CPU overhead:
static const constexpr something1 = std::string_view("Alice");
Something else?
The characters of a literal string are stored in order at contiguous memory locations. An escape sequence (such as \\ or \") within a string literal counts as a single character. A null character (represented by the \0 escape sequence) is automatically appended to, and marks the end of, each string literal.
A String Literal, also known as a string constant or constant string, is a string of characters enclosed in double quotes, such as "To err is human - To really foul things up requires a computer." String literals are stored in C as an array of chars, terminted by a null byte.
String literals. A string literal represents a sequence of characters that together form a null-terminated string. The characters must be enclosed between double quotation marks.
iostream includes string but including string explicitly is a good practice.
This is pretty short and doesn't pollute anything:
class T {
using sv = std::string_view;
static constexpr auto something1 = sv("Alice");
static constexpr auto something2 = sv("Bob");
static constexpr auto something3 = sv("Charlie");
};
If you really want to use the literal, you could wrap your class in another not-intended-to-be-named namespace
and then bring it back into the outer namespace:
namespace _private {
using namespace std::string_view_literals;
class T {
static constexpr auto something1 = "Alice"sv;
static constexpr auto something2 = "Bob"sv;
static constexpr auto something3 = "Charlie"sv;
};
}
using _private::T;
Note that writing static constexpr const
is redundant. constexpr
variables are implicitly const
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With