Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping consteval-ness of function arguments

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 ?

like image 555
Jean-Michaël Celerier Avatar asked Oct 18 '25 10:10

Jean-Michaël Celerier


1 Answers

In {fmt} 8.0 and later you can do this by using the format_string template 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)...)) {}
};
like image 127
vitaut Avatar answered Oct 20 '25 00:10

vitaut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!