[ACCEPTED]-Is it possible to choose a C++ generic type parameter at runtime?-generics
It's a compile time thing. Template parameter 9 types must be known to the compiler at compile-time.
That 8 being, said, using certain template meta-programming 7 techniques, you can choose one type or another 6 AT compile-time, but only if all possible 5 types are known at compile-time, and only 4 if the condition for selecting a type can 3 be resolved at compile time.
For example, using 2 partial specialization you could select 1 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 6 to your question is "No", C++ doesn't 5 support dynamic typing at run-time. I just 4 wanted to point out that depending on what 3 you're trying to accomplish, you may be 2 able to simulate this dynamic typing using a union, which 1 is how the VARIANT type is implemented in COM.
It is possible with Boost.Variant (fixed 16 number of different types) or Boost.Any 15 (a type that can store any type, basically 14 your "void pointer" but with type information).
It 13 is also possible if String and Integer happened 12 to be derived from a polymorphic base class. (But 11 for that they would have to implement the 10 same interface, which may or may not be 9 possible in your case.)
Generally, polymorphism 8 is the easiest way to do it, and this is 7 indeed used all the time.
Variant and Any 6 take quite a bit of work to be used: you 5 still need somehow to obtain the contents 4 as the right type they are storing. (Sort 3 of as if you were to use down-casts to derived 2 classes, instead of relying on polymorphic 1 method calls.)
I can't think of a situation where this 1 would be useful, but…
#include "boost/variant.hpp"
#include <list>
#include <string>
boost::variant<std::list<int>, std::list<std::string> >
unknown(int someval) {
if (someval == 1)
return boost::variant<std::list<int>, std::list<std::string> >(
std::list<int>());
else if (someval == 2)
return boost::variant<std::list<int>, std::list<std::string> >(
std::list<std::string>());
}
The closest you'll get is:
template <typename T>
void do_stuff_with_list
{
list<T> myList;
...
}
enum Type
{
Integer = 1,
String
};
void do_stuff(Type type)
{
switch (type)
{
case Integer:
do_stuff_with_list<int>();
break;
case String:
do_stuff_with_list<string>();
break;
};
}
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.