Conditionally disabling a copy constructor

后端 未结 6 1679
眼角桃花
眼角桃花 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:09

    A noteworthy approach is partial specialization of the surrounding class template.

    template ::value>
    struct Foo
    {
        T t;
    
        Foo() { /* ... */ }
        Foo(Foo const& other) : t(other.t) { /* ... */ }
    };
    
    template 
    struct Foo : Foo
    {
        using Foo::Foo;
    
        // Now delete the copy constructor for this specialization:
        Foo(Foo const&) = delete;
    
        // These definitions adapt to what is provided in Foo:
        Foo(Foo&&) = default;
        Foo& operator=(Foo&&) = default;
        Foo& operator=(Foo const&) = default;
    };
    

    This way the trait is_copy_constructible is satisfied exactly where T is_copy_constructible.

提交回复
热议问题