Search code examples
c++c++17variadic-templatesstatic-assertfold-expression

How to fold and static_assert all parameters?


The following doesn't compile:

  template<typename... Args>
  void check_format(Args&&... args)
  {
      static_assert((true && std::is_fundamental<decltype(args)>::value)...);
  }

Solution

  • Your attempt looks like a mix between a unary and a binary fold expression. The correct forms of the expression as either unary or binary folds are

    static_assert((... && std::is_fundamental<decltype(args)>::value));         // unary
    static_assert((true && ... && std::is_fundamental<decltype(args)>::value)); // binary
    

    The unary form works because an empty sequence is implicitly equivalent to true.

    By the way, decltype(args) is always gonna be a reference type, either lvalue or rvalue. You probably want to std::remove_reference_t from those types. And you may as well use std::remove_reference_t<Args> for ease of writing.