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

c++, dynamic, generics, templates, types

Solution

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>
}

Problem

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?

Original source