3

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?

eof
  • 133
  • 8

1 Answers1

3

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.

Indiana Kernick
  • 4,733
  • 2
  • 22
  • 47
  • Didn't know about the "sv" trick! This was exactly the kind of thing I was looking for. – eof Nov 21 '19 at 09:07