Reputation: 116
I'm trying to implement something like the following:
int x = <random integer in range [0,3]>;
<some declaration of T>
switch (x) {
case 0:
T = int;
break;
case 1:
T = double;
break;
case 2:
T = short;
break;
case 3:
T = char;
break;
default:
T = long long;
break;
}
// type of y is dependent on whatever T resolved to in switch
T y;
So I'm aware of std::conditional but the shortcoming there is that the type is dependent on a predicate which as a boolean output. I was curious if there is a standard/best practice for this situation? Thanks for any insight.
Upvotes: 0
Views: 312
Reputation: 27577
Perhaps you want a union
, perhaps you want to revisit your design....
Upvotes: 0
Reputation: 6990
It is not possible to do this. Types have to be determined compile time. C++ is stricktly typed. The only way to relax this rule is polymorphism.
Upvotes: 1
Reputation: 4853
Types are a compile time construct. If you need to be able to switch on them at run time, you need to a discriminated union such as Boost.Variant.
Upvotes: 1