std :: tie和std :: forward_as_tuple之间有什么区别

Ale*_*sky 9 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
    }
};
Run Code Online (Sandbox Code Playgroud)

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

Bar*_*rry 7

我们来看一下签名吧.std::tie()是:

template< class... Types >
constexpr tuple<Types&...> tie( Types&... args ) noexcept;
Run Code Online (Sandbox Code Playgroud)

而是std::forward_as_tuple():

template< class... Types >
constexpr tuple<Types&&...> forward_as_tuple( Types&&... args ) noexcept;
Run Code Online (Sandbox Code Playgroud)

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

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

  • @Slava它仍然是一个左值......它只是`const`.那些概念是正交的. (3认同)
  • @Slava lvalue在20世纪70年代的某个地方,当它进入C时停止了"左转任务" (2认同)
  • @slava认为它们是**L**ovely值和pi**rrrr**如果有帮助就吃了它们. (2认同)