CRTP :返回对派生类的引用
CRTP : returning a reference to the derived class?
我该用什么来替换缺少的行才能使此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
的构造函数)。
相关文章:
- 如何使用基类指针引用派生类成员
- 如何引用基类的派生类?
- 通过基类接受方法转发派生 UniquePtr 的右值会移动引用而不是复制
- 如何复制只引用基类的派生类
- 从 Base 引用对象调用派生类的成员
- C++ 为什么要将对基类的引用传递给派生类的构造函数
- 通过基类引用派生类后打印的错误值
- 如何在 c++ 中通过基类引用访问派生类的对象?
- 从基类的共享指针向下转换到派生类的引用
- 如何在模板成员中引用派生类?
- 传递指针或引用派生类,以便调用基类方法
- 通过引用派生类对象从基类对象执行向下转换时引发bad_cast异常
- 不能引用派生模板类中的基类成员
- 是否可以将常量unique_ptr引用(派生类)转换为shared_ptr(基类)
- 通过引用派生的来调用C++基实现
- 从c++中另一个(不相关的!)类的基类引用派生类的对象
- 从基类引用派生类参数
- 引用派生类中的基类成员
- 如何在指向基类对象的指针向量中引用派生对象
- C++ - 基类指针,方法指针,引用派生类,方法