Use an operator defined in base class between derived class instances

前端 未结 1 1561
小蘑菇
小蘑菇 2021-01-24 00:28

I have two classes, Base and Derived. Base defines an operator (here operator +) and I want to use it between instances of the Derived classes, but I can\'t manage to work this

相关标签:
1条回答
  • 2021-01-24 01:11

    This is a common use case for the curriously recurring template pattern. An example would be

    template<typename T>
    class Base
    {
    public:
        Base(int X) { x = X; }
    
        friend T operator+(const Base& lhs, const Base& rhs)
        {
            return T(lhs.x + rhs.x);
        }
    
        int x;
    };
    
    class Derived : public Base<Derived>
    {
    public:
        Derived(int arg) : Base(arg) { }
        using Base::Base;
    };
    
    int main()
    {
        Derived der1(1);
        Derived der2(2);
    
        Derived der3 = der1 + der2;
    
        return 0;
    }
    

    This would behave like so.

    Friend name injection (or Barton Nackman trick) is used to generate a function upon instantiation of a templated type. The above is a rough sketch of what a design could be, but I should walk you through the process of calling the + operator.

    1. der1 and der2 are converted to references to base class
    2. The body of base's operator + is selected (even if it was in a different namespace, argument dependent lookup would kick in and we would have resolution)
    3. The operator constructs a T which in this case has type Derived out of the sum

      (lhs.x + rhs.x)
      
    4. That object is used to initialize der3

    0 讨论(0)
提交回复
热议问题