使用模板化构造函数时禁用默认复制构造和赋值构造函数

Disable default copy construct & assign constructor when using templated constructors

本文关键字:构造函数 复制 赋值 默认      更新时间:2023-10-16

我试图创建一个类,这是可复制依赖于它的模板参数(bool copyable),否则它只是移动。

当通过模板参数bool Copyable启用时,它应该可以从类型本身(默认构造函数)通过myclass(myclass&&)myclass(myclass const&)进行构造。

它也应该可以从myclass用其他模板参数构造,这是我目前通过模板构造函数和赋值操作符实现的。

0规则用于通过继承的copyable helper结构体生成默认构造函数和赋值操作符,当bool Copyable为false时,该helper结构体禁用复制构造函数和复制赋值操作符。

template<bool>
struct copyable { };
template <>
struct copyable<false>
{
    // Disables copy construct & copy assign
    copyable() = default;
    copyable(copyable const&) = delete;
    copyable(copyable&&) = default;
    copyable& operator=(copyable const&) = delete;
    copyable& operator=(copyable&&) = default;
};
template<typename A, typename B, typename C>
struct storage_t
{
    // Implementation depends on A, B and C
};
template<typename A, typename B, typename C, bool Copyable>
class myclass
    : public copyable<Copyable>
{
    storage_t<A, B, C> _storage;
public:
    // It should generate the default constructors and
    // assignment operatos dependent on its inherited helper struct copyable.
    // Comment this out to disable the error...
    // (Implementation omitted)
    template<typename A, typename B, typename C>
    myclass(myclass<A, B, C, true> const&) { }
    template<typename A, typename B, typename C, bool Copyable>
    myclass(myclass<A, B, C, Copyable>&&) { }
    template<typename A, typename B, typename C>
    myclass& operator= (myclass<A, B, C, true> const&) { return *this; }
    template<typename A, typename B, typename C, bool Copyable>
    myclass& operator= (myclass<A, B, C, Copyable>&&) { return *this; }
    // ... comment end
};

通过将stackoverflow上的早期答案解释为:

    为什么模板复制构造函数覆盖默认复制构造函数?模板类的复制构造函数
  • 为什么我不能't覆盖默认的复制构造函数和赋值操作符与模板版本在c++

说:

编译器仍然会为你生成一个默认的复制构造函数,而不是实例化模板化的构造函数。

我认为编译器仍然会生成默认构造函数,尽管提供了模板化的构造函数。

但是上面的示例代码编译失败,错误消息(msvc 2015):

错误C2512: 'myclass':没有合适的默认构造函数可用:

myclass<int, int, int, true> mc1;

当我注释掉所提供的模板构造函数和赋值操作符时,使用默认构造函数,但失去了用其他模板形参赋值myclass的能力。

一个简单的用法示例是:

/////
// Testing the copyable class
myclass<int, int, int, true> mc1;
// Copy construct
myclass<int, int, int, true> mc2(mc1);
// Copy assign
mc1 = mc2;
/////
// Testing the move only class
myclass<int, int, int, false> mc3;
// Move construct
myclass<int, int, int, false> mc4(std::move(mc3));
// Move assign
mc3 = std::move(mc4);
// Not working part:
// Copy and move from myclass with other template params
myclass<int, int, float, true> mc5;
// Error here:
mc1 = mc5;

是否有一种方法可以通过模板形参禁用复制构造和赋值操作符,并提供模板化的构造函数/赋值操作符?

如果您提供其他构造函数,则不生成默认构造函数。

只提供一个默认值:

myclass() = default;

在您的例子中,如果可能的话,仍然会生成复制构造函数(当您继承copyable<false>时,情况并非如此)。