如何对可变参数模板的参数包中的值进行static_assert? [英] How do you static_assert the values in a parameter pack of a variadic template?
问题描述
我正在创建可变参数模板。
假设我有这样的东西:
I'm creating a variadic template.
Let's say I have something like this:
template<typename T, T ... Numbers>
class Sequence final {
// Unpack parameter pack into a constexpr array
constexpr static T count = sizeof...(Numbers);
constexpr static T numbers[count] = { Numbers... };
// ...
}
此实例可以实例化此类:
Instances of this class can be instantiated like:
Sequence<uint32_t, 1, 2, 3, 42, 25> seq;
我想确保在编译时使用 static_assert
,数字
参数包仅包含特定数字。就本例而言,假设我只希望允许 0
或 1
。
I'd like to make sure at compile time using a static_assert
that the numbers
parameter pack only contains specific numbers. For the sake of this example, let's say I only want to allow 0
or 1
.
所以我想做类似的事情:
So I'd like to do something like:
for (size_t i = 0; i < count; i++) {
static_assert(numbers[i] == 1 || numbers[i] == 0, "Only ones and zeroes are allowed.");
}
但显然, static_assert
不适用于 for
循环。我很确定必须为此使用某种语法,但我无法弄清楚。
But obviously, static_assert
doesn't work with a for
loop. I'm pretty sure there must be some sort of syntax for this but I haven't been able to figure it out.
我更喜欢使用可编译的内容
I'd prefer to use something that compiles with a C++11 compiler (or perhaps a C++14 compiler, if it isn't doable in C++11).
推荐答案
我将抛出 @Columbo的 bool_pack
技巧。
I'll throw in @Columbo's bool_pack
trick.
template<bool...> struct bool_pack;
template<bool... bs>
using all_true = std::is_same<bool_pack<bs..., true>, bool_pack<true, bs...>>;
static_assert(all_true<(Numbers == 0 || Numbers == 1)...>::value, "");
如果满足以下条件,则将表达式提取到 constexpr
函数中它变得复杂。
Extract the expression into a constexpr
function if it gets complex.
这篇关于如何对可变参数模板的参数包中的值进行static_assert?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!