c++ - std::tie 和 std::forward_as_tuple 有什么区别

标签 c++ c++14

对于一个给定的类,如果我想写所有的比较运算符,为了避免代码重复,我会这样写:

class B {
public:
    bool operator==(Type const& rhs) const {
        return as_tuple() == rhs.as_tuple();
    }

    bool operator!=(Type const& rhs) const {
        return as_tuple() != rhs.as_tuple();
    }

    // .. and same for other operators ..

private:
    auto as_tuple() const {
        return std::tie(a, b, c); // all the members
    }
};

我可以用 std::tie() 实现 as_tuple() 或者我可以用 std::forward_as_tuple() 实现它.有区别吗?我应该选择哪个?

最佳答案

让我们看看签名。 std::tie() 是:

template< class... Types >
constexpr tuple<Types&...> tie( Types&... args ) noexcept;

鉴于 std::forward_as_tuple() 是:

template< class... Types >
constexpr tuple<Types&&...> forward_as_tuple( Types&&... args ) noexcept;

唯一的区别是前者只接受左值,而后者接受左值和右值。如果您的所有输入都是左值,就像它们在您的用例中一样,那么它们是完全等价的。

std::tie()主要用作赋值的左侧(例如 std::tie(a, b) = foo; 解压 pair ),而 std::forward_as_tuple()主要是为了在函数中传递东西以避免复制。但是它们都可以用来解决这个问题。 tie显然要短一些,而且可以说更广为人知(tie 的 cppreference 示例使用它来实现 operator< ),所以我会投票。

关于c++ - std::tie 和 std::forward_as_tuple 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51971003/

相关文章:

c++ - C++ 中返回简单哈希码的函数

c++ - 在 C++ 中找到给出错误答案的方法

c++ - 当 `new v < new v` 不是模板时,为什么 gcc 拒绝 `v`?

c++ - 在运行时组合规则并返回规则

c++ - 如何在释放按钮时仅发送一次变量值?

c++ - 尝试使用类 (SDL)

c++ - C++中整数文字的内存地址

C++ 编译器允许循环定义?

使用 std::vector 的 c++ 矩阵初始化

c++ - sizeof 对齐的空结构