Multiple dispatch in C++

前端 未结 3 757
梦毁少年i
梦毁少年i 2020-11-27 04:29

I am trying to understand what multiple dispatch is. I read a lot of various texts but I still have no idea what multiple dispatch is and what it is good for. Maybe the thin

3条回答
  •  温柔的废话
    2020-11-27 04:53

    In single dispatch the function executed depends on just the object type. In double dispatch the function executed depends on the object type and a parameter.

    In the following example, the function Area() is invoked using single dispatch, and Intersect() relies on double dispatch because it takes a Shape parameter.

    class Circle;
    class Rectangle;
    class Shape
    {
        virtual double Area() = 0; // Single dispatch
    
        // ...
        virtual double Intersect(const Shape& s) = 0; // double dispatch, take a Shape argument
        virtual double Intersect(const Circle& s) = 0; 
        virtual double Intersect(const Rectangle& s) = 0; 
    };
    
    struct Circle : public Shape
    {
        virtual double Area() { return /* pi*r*r */; }
    
        virtual double Intersect(const Shape& s); 
        { return s.Intersect(*this)  ; }
        virtual double Intersect(const Circle& s); 
        { /*circle-circle*/ }
        virtual double Intersect(const Rectangle& s); 
        { /*circle-rectangle*/ }
    };
    

    The example is based on this article.

提交回复
热议问题