What are some 'good use' examples of dynamic casting?

后端 未结 6 2255
攒了一身酷
攒了一身酷 2020-12-09 03:29

We often hear/read that one should avoid dynamic casting. I was wondering what would be \'good use\' examples of it, according to you?

Edit:

Yes, I\'m aware

6条回答
  •  情话喂你
    2020-12-09 03:52

    Here's something I do often, it's not pretty, but it's simple and useful.

    I often work with template containers that implement an interface, imagine something like

    template
    class MyVector : public ContainerInterface
    ...
    

    Where ContainerInterface has basic useful stuff, but that's all. If I want a specific algorithm on vectors of integers without exposing my template implementation, it is useful to accept the interface objects and dynamic_cast it down to MyVector in the implementation. Example:

    // function prototype (public API, in the header file)
    void ProcessVector( ContainerInterface& vecIfce );
    
    // function implementation (private, in the .cpp file)
    void ProcessVector( ContainerInterface& vecIfce)
    {
        MyVector& vecInt = dynamic_cast >(vecIfce); 
        // the cast throws bad_cast in case of error but you could use a
        // more complex method to choose which low-level implementation
        // to use, basically rolling by hand your own polymorphism.
    
        // Process a vector of integers
        ...
    }
    

    I could add a Process() method to the ContainerInterface that would be polymorphically resolved, it would be a nicer OOP method, but I sometimes prefer to do it this way. When you have simple containers, a lot of algorithms and you want to keep your implementation hidden, dynamic_cast offers an easy and ugly solution.

    You could also look at double-dispatch techniques.

    HTH

提交回复
热议问题