2

Does C++17 provide a way to get the type from a typeid or is the factory pattern still the only methodology?

RFS
  • 311
  • 3
  • 8
  • Do you mean the implementation defined `name()` of the `std::type_info`? – Eljay Nov 17 '19 at 20:18
  • 4
    Remember that C++ is statically typed, so if you want to use a type in an expression you must know that type at compile-time. What would you use this for? An adequate answer is more likely if you give details on the use case. – walnut Nov 17 '19 at 20:18
  • I have a map in which I want to store a large variety of templated objects. I have these classes inherit from an unparameterized base class, which allows me store them all in the same map. When I retrieve an object, how can I determine its type? – RFS Nov 17 '19 at 20:45
  • 3
    @RFS You shouldn't really need to, because the base class should be a virtual interface that is used by the user of the map directly. If that is not the case, then you should probably not be using inheritance for polymorphism, but e.g. `std::variant`. – walnut Nov 17 '19 at 20:51
  • 1
    If you really need to do the way you are describing, then https://stackoverflow.com/questions/351845/finding-the-type-of-an-object-in-c or https://stackoverflow.com/questions/307765/how-do-i-check-if-an-objects-type-is-a-particular-subclass-in-c should be a duplicates. – walnut Nov 17 '19 at 20:54

1 Answers1

2

type_info is a runtime value; its exact contents can only be determined via runtime execution. C++ is a statically typed language; at compile time, the type of everything must be known. As such, type_info-based reification (the ability to take a description of a thing and turn it into the thing itself) is not going to ever happen in C++.

C++ will likely get reflection and reification mechanisms in the future, but they will only be static mechanisms, not runtime mechanisms.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982