oar*_*ish 3 c++ templates variadic-templates c++20
我想在可能固定数量的布尔值上模板化一个类,对它们进行计数,然后使用该数字作为基类的模板参数。像这样的东西
\ntemplate <int Dimensionality> struct Foo {}; // I want to inherit from this\n\n// helpers to compile-time count the true values among bools\ntemplate <bool B, bool... Args>\nstruct count_true {\n static constexpr int value = count_true<B>::value + count_true<Args...>::value;\n};\n\ntemplate <>\nstruct count_true<true> {\n static constexpr int value = 1;\n};\ntemplate <>\nstruct count_true<false> {\n static constexpr int value = 0;\n};\n\n// I want something like this, pseudocode\ntemplate <bool... Args>\nstruct Bar : public Foo<count_true<Args...>::value> {\n Bar(bool... args) {\n // do something with the parameters\n static_assert(sizeof...(args) <= 1337);\n }\n};\n
Run Code Online (Sandbox Code Playgroud)\n但我找不到办法做到这一点。\n似乎有很多与使用enable_if
for 参数包有关的问题,例如
或者在模板类型不用于继承的地方使用,例如
\n但在这种特殊情况下,这些都没有帮助。\n“伪代码”无法编译,因为bool... args
不是未扩展的参数包。
我想这样的东西可能会起作用,但事实并非如此,因为参数包必须是最后一个模板参数:
\ntemplate <class... Ts>\nstruct Bar : public Foo<count_true<Ts..., std::enable_if_t<(std::is_same<Ts, bool>::value && ...), bool>>::value> {\n\xe2\x80\xa6\n}\n
Run Code Online (Sandbox Code Playgroud)\n有办法做到这一点吗?这个问题可能有点困惑,因为我真的不知道我在做什么模板元编程。
\n但在这个特殊情况下,这些都没有帮助。“伪代码”无法编译,因为
bool
... args 不是未扩展的参数包。
您可以使用 扩展模板参数decltype()
。此外,count_true
可以简单地用折叠表达式替换。
template <bool... Args>
struct Bar : public Foo<(Args + ... + 0)> {
Bar(decltype(Args)... args) {
// do something with the parameters
static_assert(sizeof...(args) <= 1337);
}
};
Run Code Online (Sandbox Code Playgroud)