Why is usage of the typeid keyword bad design?

前端 未结 3 1115
不思量自难忘°
不思量自难忘° 2021-01-02 03:17

I have heard a lot of people say any usage of typeid is bad design, yet to me it seems like it offers great utility.

  1. When (and why) is usage of
3条回答
  •  臣服心动
    2021-01-02 03:53

    It's too bad that those who gave you this good advice couldn't give the reasons for it. It means they're simple cargo cult programmers.

    All expressions have a static compile-time type (after template expansion). All types are either polymorphic or not.

    I'll try to elaborate for you why typeid is (the closest thing to) useless in both cases:

    1. There is no reason to use typeid when the expression's static type is not polymorphic. The compiler will use the static type, not the dynamic type, so compile-time function overloading works. And type identity can be checked much more efficiently using a templated type trait such as is_same.

    2. If the static type of the expression is polymorphic, then typeid fails. Yes, it will give information on the dynamic type of the object. But only the most derived dynamic type. This violates the Liskov Substitution Principle, since given types Base and Child, adding a new type Grandchild derived from Child will not be treated as Child is. The Open-Closed principle is also violated, since the design cannot be extended with new types without rewriting everything. There is no encapsulation, since information about the class hierarchy must be scattered throughout the program, creating strong coupling. dynamic_cast overcomes some but not all of these problems.

    In short, a program that uses typeid will be very difficult to maintain and test.

    And, as with any rule, there may be limited exception. Where you're using OO language features of inheritance and virtual functions, but you don't actually want a polymorphic design. I can think of exactly one: where you want to log the name of the type as a string, using type_info::name(). You might also be able to use it to detect slicing (where polymorphism is already violated). But this is good for debugging only, never for controlling program flow.

提交回复
热议问题