“type-switch” construct in C++11

后端 未结 5 1983
自闭症患者
自闭症患者 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 05:02

    Some time ago I was experimenting to write a library for doing exactly that.

    You can find it here:

    https://github.com/nicola-gigante/typeswitch

    The project was quite ambitious, with a lot of planned features, and it still needs to be finished (there's also an important bug that I already know, but I don't have time to work on it anymore in this months). However, for your use case of a classic hierarchy of classes, it would work perfectly (I think).

    The basic mechanism is the same as you have posted before, but I try to extend the concept with more features:

    • You can provide a default case that is called if no other clause matches.
    • You can return a value from the clauses. The return type T is the common type of the types returned by all the clauses. If there's no default case, the return type is optional instead of T.
    • You can choose between boost::optional or any implementation of std::experimental::optional from the current draft of the Library Foundamentals TS (for example, libc++ provides one).
    • You can match multiple parameters at once.
    • You can match the type contained in a boost::any object.
    • You can hook the type switch with a custom casting mechanism, to override the dynamic_cast. This is useful when using libraries that provide their own casting infrastructure, like Qt's qobject_cast, or to implement the typeswitch on your own tagged unions or anything like that.

    The library is quite finished, except for a bug that is documented in the README that makes impossible to match non-polymorphic types with static overloading resolution rules, but it's a case that would only be useful in templated generic code, and is not involved in the majority of use cases like yours. I currently don't have time to work on it to fix the bug, but I suppose it's better to post it here than leave it unused.

提交回复
热议问题