有没有办法比较可变参数模板的每种类型的值?
template<typename... S>
class Signature {
// this is not valid syntax
S... values;
bool equals(S... s) {
// this is not either
bool eq = true;
eq &= s... &= values...;
return eq;
}
};
例子:
Signature<int, bool> s(5, true);
s.equals(5, true); // should result in 1
最佳答案
这个:
S... values;
格式错误。你不能有这样的包声明(不幸的是)。你必须把所有的值都放在一些东西里,比如:
std::tuple<S...> values;
一旦你这样做了,比较它们就很简单了。只需使用 ==
:
template<typename... S>
struct Signature {
std::tuple<S...> values;
bool equals(Signature<S...> const& rhs) const {
return values == rhs.values;
}
bool equals(S const&... rhs) const {
// forward here to produce a tuple<S const&...> and avoid an unnecessary copy
return values == std::forward_as_tuple(rhs...);
}
};
关于c++ - 按值比较可变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46391517/