CRTP:返回对派生类的引用?

时间:2012-08-17 16:05:38

标签: c++ casting operator-overloading crtp

我有什么要更换丢失的行以使这个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>
{
};

其他问题:您提供的解决方案是否会在运行时产生成本(与在派生类中直接实现运算符的解决方案相比)?

非常感谢。

1 个答案:

答案 0 :(得分:1)

return static_cast<Crtp&>(*this);

这在运行时没有成本(但您可能希望保护Base的构造函数。)