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

Den*_*ank 5 c++ templates c++14

我正在尝试创建一个可复制的类,具体取决于其模板参数(bool Copyable),否则它只能移动。

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

它还可以myclass使用其他模板参数进行构造,我当前的实现通过模板化构造函数和赋值运算符涵盖了这一点。

这里使用零规则通过继承的copyable辅助结构生成默认构造函数和赋值运算符,当为 false 时,该结构将禁用复制构造函数和复制赋值运算符bool Copyable

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
};
Run Code Online (Sandbox Code Playgroud)

通过解释 stackoverflow 上的早期答案,例如:

其中说:

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

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

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

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

myclass<int, int, int, true> mc1;
Run Code Online (Sandbox Code Playgroud)

当我对提供的模板化构造函数和赋值运算符进行注释时,将使用默认构造函数,但无法使用其他模板参数分配 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;
Run Code Online (Sandbox Code Playgroud)

有没有办法禁用通过模板参数描述的复制构造和赋值运算符,并提供模板化构造函数/赋值运算符?

Jar*_*d42 2

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

只需提供一个默认值:

myclass() = default;
Run Code Online (Sandbox Code Playgroud)

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