“type-switch” construct in C++11

后端 未结 5 1987
自闭症患者
自闭症患者 2020-12-14 04:35

All the time, I find myself doing something like this:

Animal *animal = ...
if (Cat *cat = dynamic_cast(animal)) {
    ...
}
else if (Dog *dog =         


        
5条回答
  •  醉话见心
    2020-12-14 04:38

    Implementation

    template 
    void action_if(B* value, std::function action)
    {
        auto cast_value = dynamic_cast(value);
        if (cast_value != nullptr)
        {
            action(cast_value);
        }
    }
    

    Usage

    Animal* animal = ...;
    action_if(animal, [](Cat* cat)
    {
        ...
    });
    action_if(animal, [](Dog* dog)
    {
        ...
    });
    

    I don't have access to a C++11 compiler right this second to try this out, but I hope the idea is useful. Depending on how much type inference the compiler is capable of, you may or may not have to specify the case's type twice - I'm not C++11-pro enough to tell from looking at it.

提交回复
热议问题