Reputation: 153
I'd like to accomplish something like the following:
#define FOO(bar, ...) \
static_assert(bar == "foo" || bar == "bazz", "Invalid value for bar") \
...
In other words, I'd like to check at compile time that the value given to the macro is one of the allowed ones. What is the cleanest way for doing a compile time string comparison when comparing against strings of variable length?
Upvotes: 3
Views: 193
Reputation: 5331
You could use string views.
#include <string_view>
using namespace std::string_view_literals;
// Note the sv after the string
#define FOO(bar, ...) \
static_assert(bar == "foo"sv || bar == "bazz"sv, "Invalid value for bar") \
...
The expression "foo"sv
invokes a literal operator. It constructs a std::string_view
from "foo"
. std::string_view
has overloaded ==
operators for comparing with strings. These overloaded operators are constexpr
which means that they can be evaluated at compile time.
Upvotes: 3