【问题标题】:How to fold and static_assert all parameters?如何折叠和static_assert所有参数?
【发布时间】:2019-10-10 13:26:34
【问题描述】:
以下内容无法编译:
template<typename... Args>
void check_format(Args&&... args)
{
static_assert((true && std::is_fundamental<decltype(args)>::value)...);
}
【问题讨论】:
标签:
c++
c++17
variadic-templates
static-assert
fold-expression
【解决方案1】:
这应该可行:
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{}));
}
【解决方案2】:
您的尝试看起来像是一元和二元折叠表达式的混合。作为一元或二元折叠的表达式的正确形式是
static_assert((... && std::is_fundamental<decltype(args)>::value)); // unary
static_assert((true && ... && std::is_fundamental<decltype(args)>::value)); // binary
一元形式有效,因为空序列隐式等效于true。
顺便说一句,decltype(args) 始终是引用类型,无论是左值还是右值。您可能想从这些类型中std::remove_reference_t。并且您也可以使用std::remove_reference_t<Args> 以方便编写。