c++ - 按值比较可变参数

标签 c++ c++11 variadic-templates

有没有办法比较可变参数模板的每种类型的值?

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/

相关文章:

c++ - 哪个是更专业的模板功能? clang 和 g++ 对此有所不同

c# - 是否有任何免费的 C++ 和/或 C# 编译器可以在支持 Android 的平板电脑上运行?

c++ - 堆分配的对象可以在堆栈上 move 吗?

c++ - Clang 不能使用花括号初始化来进行用户定义的转换

c++ - 返回分配的局部变量

c++ - 检查是否有效的模板特化

c++ - 使用 FindFirstFile 和 FindNextFile 递归查找具有特定扩展名的文件

c++ - Code::Blocks 编译错误

c++ - 在 clang 中强制使用 `const char[]` 字符串文字

c++ - 使用可变参数模板以更多参数概括 STL 算法