Yoda
Yoda

Reputation: 18068

How to change type of int to double in c++

Is there any way to initialize a variable as a general number type or int and then change its type to double for example?

TYPE x = 4;
// commands changing its type
here it(variable x) became double.

I know it is weird.

The variable has to have the same name.

Upvotes: 0

Views: 5295

Answers (2)

Paul Michalik
Paul Michalik

Reputation: 4381

Though it is not possible to change the type of a variable, you can define a type capable of representing variables of various types. This is generally called a variant. Go and get Boost.Variant which allows you to write code like this:

boost::variant<int, double> t_either_int_or_double;

t_either_int_or_double = 1;

// now it is "int"
assert(boost::get<int>(t_either_int_or_double);

t_either_int_or_double = 1.0;

// now it is "double"
assert(boost::get<double>(t_either_int_or_double);

Upvotes: 2

anon
anon

Reputation:

No. C++ is a statically typed languages. The type is fixed when the variable is declared.

You could kind of do what you describe using a union, but great care is required, e.g.

union DoubleInt
{
  int i;
  double d;
};

DoubleInt X;
X.i = 4;

// ... whatever

X.d = X.i;
X.d += 0.25;

But unions are really only a sensible option where you're desperate to bit pack. You could also create a class that can behave as either a double or int but, really, what you're talking about doing doesn't sound like you're thinking in a C++ way.

Finally, boost::variant might do what you want?

Upvotes: 10

Related Questions