首页 > 解决方案 > 如何折叠和static_assert所有参数?

问题描述

以下内容无法编译:

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

标签: c++c++17variadic-templatesstatic-assertfold-expression

解决方案


这应该有效:

static_assert((std::is_fundamental_v<Args> && ...));

Godbolt 的更长示例:https ://gcc.godbolt.org/z/9yNf15

#include <type_traits>

template<typename... Args>
constexpr bool check_format(Args&&... args)
{
    return (std::is_fundamental_v<Args> && ...);
}

int main() {
    static_assert(check_format(1, 2, 3));
    static_assert(check_format(nullptr));
    static_assert(!check_format("a"));
    static_assert(check_format());
    struct Foo {};
    static_assert(!check_format(Foo{}));
}

推荐阅读