[英]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)...);
}
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
作为一元或二元折叠的表达式的正确 forms 是
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
.一元形式有效,因为空序列隐式等效于
true
。
By the way, decltype(args)
is always gonna be a reference type, either lvalue or rvalue.顺便说一句,
decltype(args)
总是会是一个引用类型,无论是左值还是右值。 You probably want to std::remove_reference_t
from those types.您可能想从这些类型中
std::remove_reference_t
。 And you may as well use std::remove_reference_t<Args>
for ease of writing.您也可以使用
std::remove_reference_t<Args>
以便于编写。
This should work:这应该有效:
static_assert((std::is_fundamental_v<Args> && ...));
Longer example on godbolt: https://gcc.godbolt.org/z/9yNf15 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{}));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.