C++ - 父级中的 CRTP 赋值运算符不起作用

C++ - CRTP assign operator in parent not working

我有这个 类 使用 CRTP(代码是虚拟的,仅用于演示问题):

template <class T>
struct IFoo 
{
    IFoo() {}
    IFoo(const char * x) {}

    //T & operator=(const char * x){ return *static_cast<T *>(this); } //not working

    void Test() { static_cast<T *>(this)->TestInternal(); }
};


struct Bar : public IFoo<Bar>
{
    using IFoo<Bar>::IFoo;

    Bar(const Bar & b) {}
    Bar(const Bar && b) {}

    //Bar & operator=(const char * x){ return *this;} //works

    void TestInternal(){}
};

和代码:

Bar bar = "bar";
bar = "bar2"; //not working if assign operator is in IFoo

如果我在 Bar 中使用赋值运算符,上面的代码是有效的。但是,在 IFoo 中使用赋值运算符不是这样,我得到了错误:

error C2280: 'Bar &Bar::operator =(const Bar &)': attempting to reference a deleted function
note: compiler has generated 'Bar::operator =' here
note: 'Bar &Bar::operator =(const Bar &)': function was implicitly deleted because 'Bar' has a user-defined move constructor 

为什么?

最简单的解决方案是 using 基本运算符,就像您当前 using 基本构造函数一样:

using IFoo<Bar>::operator=;

之前的响应将使您的代码正常工作。

但我想注释掉 CRTP 和静态转换中的一些内容。 我会提出以下建议: 使构造函数在重复模式上私有,以避免不良使用,尤其是在转换时。 然后你可以从 derived 作为 friend class 访问构造函数,即使它是非法的你也可以创建一个包装器。

template <typename T>
struct wrapper {
    typedef T type;
};

template <class T>
struct IFoo 
{
    typedef T temp;
    friend class wrapper<temp>::type;
private:
    IFoo() {}
    IFoo(const char * x) {}
    public:
    T & operator=(const char * x){ return *static_cast<T *>(this); } //not working

    void Test() { static_cast<T *>(this)->TestInternal(); }
};


struct Bar : public IFoo<Bar>
{
    //using IFoo<Bar>::IFoo;
    using IFoo<Bar>::operator=;

    Bar() {}
    Bar(const char *x) {}
    Bar(const Bar & b) {}
    Bar(const Bar && b) {}

    //Bar & operator=(const char * x){ return *this;} //works

    void TestInternal(){}
};

int main () {
     Bar bar = "bar";
     bar = "bar";
}