Conditionally disabling a copy constructor

后端 未结 6 1663
眼角桃花
眼角桃花 2020-12-08 04:34

Suppose I\'m writing a class template C that holds a T value, so C can be copyable only if T is copyabl

6条回答
  •  眼角桃花
    2020-12-08 05:04

    However, it's not always possible to structure your class so that defaulted constructors will do the right thing.

    It's usually possible with enough effort.

    Delegate the work that can't be done by a defaulted constructor to another member, or wrap the T member in some wrapper that does the copying, or move it into a base class that defines the relevant operations.

    Then you can define the copy constructor as:

      C(const C&) = default;
    

    Another way to get the compiler to decide whether the default definition should be deleted or not is via a base class:

    template
    struct copyable_characteristic { };
    
    template<>
    struct copyable_characteristic {
      copyable_characteristic() = default;
      copyable_characteristic(const copyable_characteristic&) = delete;
    };
    
    template 
    class C
    : copyable_characteristic::value>
    {
     public:
      C(const C&) = default;
      C(C&& rhs);
    
      // other stuff
    };
    

    This can be used to delete operations using arbitrary conditions, such as is_nothrow_copy_constructible rather than just a straightforward T is copyable implies C is copyable rule.

提交回复
热议问题