gpt4 book ai didi

c++ - 折叠表达式 : iterate over variadic template type parameter to check compile-time conditions on the comprising types

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:54 28 4
gpt4 key购买 nike

我的想法很简单:在可变类模板中,我想检查类型的一些编译时条件。在这种情况下,我想知道包中是否包含某种类型。这就是使用 C++17 的折叠表达式的代码可能看起来的样子,但显然这不是有效的语法。如何实现?

#include <type_traits>

template <class... Types>
struct TypesPack
{
template <typename T>
static constexpr bool hasType() {
return std::is_same<T, Types>::value || ... || false;
}
};

最佳答案

static constexpr bool hasType() {
return (std::is_same<T, Types>::value || ...);
}

折叠表达式必须加括号,并且在使用 || 作为运算符时允许省略 false

关于c++ - 折叠表达式 : iterate over variadic template type parameter to check compile-time conditions on the comprising types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53254029/

28 4 0