Is it possible to choose a C++ generic type parameter at runtime?

后端 未结 5 697
天命终不由人
天命终不由人 2021-02-14 07:52

Is there a way to choose the generic type of a class at runtime or is this a compile-time thing in C++?

What I want to do is something like this (pseudocode):

         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-14 08:33

    It is possible with Boost.Variant (fixed number of different types) or Boost.Any (a type that can store any type, basically your "void pointer" but with type information).

    It is also possible if String and Integer happened to be derived from a polymorphic base class. (But for that they would have to implement the same interface, which may or may not be possible in your case.)

    Generally, polymorphism is the easiest way to do it, and this is indeed used all the time.

    Variant and Any take quite a bit of work to be used: you still need somehow to obtain the contents as the right type they are storing. (Sort of as if you were to use down-casts to derived classes, instead of relying on polymorphic method calls.)

提交回复
热议问题