Home > Net >  Keeping consteval-ness of function arguments
Keeping consteval-ness of function arguments

Time:10-17

I am using the neat fmt library, which in its version 8, does compile-time checking of its format string if the compiler supports the relevant features.

I would, at some point, like to write the following code:

throw my_exception("error: {}", 123);

Sadly, the naive implementation:

struct my_exception : std::runtime_error {
  template<typename... Args>
  my_exception(Args&&... args)
    : std::runtime_error{fmt::format(std::forward<Args>(args)...)} 
  { }
};

fails, as this looses the "consteval-ness" of the string literal argument, which is required by fmt::format. For now, I settled on the following:

template<std::size_t N>
struct literal {
  constexpr literal(const char (&str)[N]) noexcept {
    std::copy_n(str, N, this->str);
  }

  char str[N];
};

template<literal lit>
struct exception : std::runtime_error {
  template<typename... Args>
  exception(Args&&... args)
    : std::runtime_error{fmt::format(lit.str, std::forward<Args>(args)...)}
  {

  }
};

which gets called like

throw my_exception<"foo {}">(123);

How can I get back a normal function call syntax, while keeping the compile-time checking ?

CodePudding user response:

You can do it by using the format_string type that, as the name suggests, represents a format string (https://godbolt.org/z/bqvvMMnjG):

struct my_exception : std::runtime_error {
  template <typename... T>
  my_exception(fmt::format_string<T...> fmt, T&&... args)
    : std::runtime_error(fmt::format(fmt, std::forward<T>(args)...)) {}
};
  • Related