user1373317
user1373317

Reputation: 116

C++ variable type selection depending on switch

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

Answers (3)

Paul Evans
Paul Evans

Reputation: 27577

Perhaps you want a union, perhaps you want to revisit your design....

Upvotes: 0

Jacques de Hooge
Jacques de Hooge

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

Nevin
Nevin

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

Related Questions