CRTP :返回对派生类的引用

CRTP : returning a reference to the derived class?

本文关键字:引用 派生 返回 CRTP      更新时间:2023-10-16

我该用什么来替换缺少的行才能使此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 的构造函数)。