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):
Generictype type;
if(somveval==1)
type = Integer;
if(someval==2)
type = String;
list<type> myList;
Is this possible in C++? and if yes, how?
It's important to realize that generic type information is only available to the compiler, not the JVM. In other words, type erasure means that generic type information is not available to the JVM at runtime, only compile time.
To examine a generic type and its type parameters Get an instance of Type that represents the generic type. In the following code, the type is obtained using the C# typeof operator ( GetType in Visual Basic, typeid in Visual C++). See the Type class topic for other ways to get a Type object.
The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.
The generic argument list is a comma-separated list of type arguments. A type argument is the name of an actual concrete type that replaces a corresponding type parameter in the generic parameter clause of a generic type. The result is a specialized version of that generic type.
It's a compile time thing. Template parameter types must be known to the compiler at compile-time.
That being, said, using certain template meta-programming techniques, you can choose one type or another AT compile-time, but only if all possible types are known at compile-time, and only if the condition for selecting a type can be resolved at compile time.
For example, using partial specialization you could select a type at compile time based on an integer:
template <typename T>
class Foo
{ };
template <int N>
struct select_type;
template<>
struct select_type<1>
{
typedef int type;
};
template<>
struct select_type<2>
{
typedef float type;
};
int main()
{
Foo<select_type<1>::type> f1; // will give you Foo<int>
Foo<select_type<2>::type> f2; // will give you Foo<float>
}
As others have also responded, the answer to your question is "No", C++ doesn't support dynamic typing at run-time. I just wanted to point out that depending on what you're trying to accomplish, you may be able to simulate this dynamic typing using a union, which is how the VARIANT type is implemented in COM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With