Overload operator in template base class

吃可爱长大的小学妹 提交于 2019-12-06 15:20:10

Curiously, clang accepts your code. This works in both, gcc and clang:

Base& operator=(const Base& o) {
    std::cout << "operator=" << std::endl;
    memcpy(self().a, o.self().a, self().size);
    return *this;
}

T& self() {
    return static_cast<T&>(*this);
}

const T& self() const {
    return static_cast<const T&>(*this);
}

BTW, a virtual destructor looks odd here: you're mixing compile-time polymorphism (via CRTP) with run-time polymorphism (via virtual). Probably, you don't need it.

Edit.

As @n.m. judiciously pointed in the comment, although this code compiles, it's broken because default-generated copy assignment operator is still there. So, in the derived class we should define copy assignment explicitly:

Der& operator=(const Der& o)
{
    Base<Der...>::operator=(o);
    return *this;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!