Is there a way to pass a typeid return directly to a cast (with some clunky if else if block)? Something similar to the following is what I'm wondering about (but that works!):
1 2 3 4
int i(0);
float j(0.0f);
i = static_cast<typeid(i)>(j);
If this is not possible with typeid is there and equivalent function that will allow dynamic determination of type in a form that is acceptable by a casting operator?
C++ is a statically typed language, meaning that types of variables are always known at compiler time and such thing would never be needed. In some cases though, you may not know the real type of an object being pointed to (that is the case Base* my_base_ptr = &my_object_derived_from_base;). Then you can use dynamic_cast to see if that Base* really points to a Derived object.
hamsterman, what I'm trying to do is use a template function which treats different types differently, and I was hoping to do this within a switch statement rather than specialized templates due to the number of options (smaller SLOC this way).
Cubbi, thank you that is exactly what I'm looking for! Unfortunately our current project compiler does not support C++11 as of this point, so I guess in the meantime I'll have to use specialization for now. I'll make a note of this so I can use it as soon as available.
On a side note, would specialization be more optimized than using decltype within a switch statement? If so maybe I should go ahead with the specialization even when C++11 becomes available to me.
Again, unless you're dealing with polymorphism, type is known at compile time. You don't need anything dynamic. And since you considered template specializations, you must understand that.
To save lines of code, I suggests this: