【问题标题】:Move constructor for a value/object wrapper?移动值/对象包装器的构造函数?
【发布时间】:2013-01-10 08:54:51
【问题描述】:

考虑以下类:

template <typename Type>
class Wrapper
{
    public:
        Wrapper(const Type& x) : _data(x) {;}
        Wrapper<Type>& operator=(const Type& x) {_data = x; return *this;}
    protected:
        Type _data;
};

这个类的移动构造函数Wrapper(Type&amp;&amp; x)和移动赋值运算符operator=(Type&amp;&amp; x)的定义是什么?

【问题讨论】:

  • 类定义中不需要拼出模板参数;这是隐含的。

标签: c++ c++11 constructor assignment-operator move-semantics


【解决方案1】:
Wrapper(Type&& x) : _data(std::move(x)) {}
Wrapper& operator=(Type&& x) {_data = std::move(x); return *this;}

【讨论】:

    【解决方案2】:

    用 C++11 编写此代码的一种有趣方式是:

    template<typename A, typename B, typename T=void*>
    using IfSameBaseType = std::enable_if<
      typename std::is_same<
        typename std::remove_cv<A>::type,
        typename std::remove_cv<B>::type
      >::type,
      T
    >::type;
    
    template <typename T>
    class Wrapper
    {
      public:
        template<typename U, typename unused>
        Wrapper(U&& u, unused* do_not_use=(IfSameBaseType<T,U>*)nullptr) :
          data_( std::forward(u) )
        {}
        template<typename U>
        IfSameBaseType<T,U,Wrapper<Type>>& operator=(U&& x) {
          data_ = std::forward(x);
          return *this;
        }
      protected:
        T data_;
    };
    

    在这里,我在类型推导上下文中使用 &amp;&amp; 为 l 和 r 值引用提供单个覆盖,然后通过 std::forward 传递。 IsSameBaseType 的东西只是确保我只为 T 类型编写构造函数——我可以扩展它并说“可以隐式转换为 T”而不是 IsSameBaseType,而不会有那么多麻烦。

    这样做的好处是我们有更少的重复方法。缺点是模板愚蠢会分散人们的注意力。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-08
      • 2021-09-15
      • 2021-08-15
      • 2023-04-08
      • 2011-05-04
      • 2020-03-22
      • 1970-01-01
      • 2018-12-13
      相关资源
      最近更新 更多