Conditionally disabling a copy constructor

后端 未结 6 1682
眼角桃花
眼角桃花 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 04:52

    This is a bit of a trick, but it works.

    template
    struct block_if_helper{
      using type=T;
    };
    template
    struct block_if_helper{
      class type{
        type()=delete;
      };
    };
    template
    using block_if=typename block_if_helper::type;
    template
    using block_unless=typename block_if_helper::type;
    

    now we create a method that is your copy ctor ... maybe.

    template
    struct example {
      enum { can_copy = std::is_same{} };
    
      example( block_unlessconst& o ); // implement this as if `o` was an `example`
      // = default not allowed
      example( block_ifconst& )=delete;
    };
    

    and now the =default is the copy ctor if and only if can_copy, and the =delete of not. The stub type that it is otherwise cannot be created.

    I find this technique useful for general method disabling on compilers that do not support the default template argument feature, or for methods (like virtual or special) that cannot be templates.

提交回复
热议问题