我该用什么替换缺少的行才能使此CRTP解决方案正常工作?
template<class Crtp> class Base
{
public:
inline Crtp& operator=(const Base<Crtp>& rhs)
{
for (unsigned int i = 0; i < const_size; ++i) {
_data[i] = rhs._data[i];
}
return /* SOMETHING HERE BUT WHAT ? */
}
protected:
static const unsigned int const_size = 10;
double _data[const_size];
};
class Derived : public Base<Derived>
{
};
另一个问题:您将提供的解决方案在运行时是否有成本(与在派生类中直接实现运算符的解决方案相比)?
非常感谢你。
最佳答案
return static_cast<Crtp&>(*this);
这在运行时没有成本(但是您可能想要保护
Base
的构造函数)。关于c++ - CRTP:返回对派生类的引用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12009257/