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