“type-switch” construct in C++11

后端 未结 5 1978
自闭症患者
自闭症患者 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

    I think it depends if you want do this at compile time or at run time. For compile time, Verdagon's answer is better, at runtime you can do something like this

    class A {
    };
    
    class B {
    };
    
    void doForA() {
        std::cout << "I'm A" << std::endl;
    }
    
    void doForB() {
        std::cout << "I'm B" << std::endl;
    }
    
    int main() {
        std::unordered_map> mytypes;
        mytypes[typeid(A)] = doForA;
        mytypes[typeid(B)] = doForB;
    
        mytypes[typeid(A)]();
    }
    

    but both ways are wrong the virtual keyword is here for this, you MUST do like Arie said or there is mistake in your architecture

提交回复
热议问题