Storing int and double type values under one variable name

This is a discussion on Storing int and double type values under one variable name within the C++ Programming forums, part of the General Programming Boards category; I want to get inputs to a variable called “quantity”. The user can input it either in int or double ...

Storing int and double type values under one variable name

I want to get inputs to a variable called “quantity”. The user can input it either in int or double types and the program needs to differentiate the type. Can I do it with C++?
For the moment, I have used an abstract base class in which the proper type can be Input when the type is given.
But what I want to do it keep both type under one particular variable in a Different class.
Ex.

Assuming your data is of a basic type (float, double, int, etc) look up the notion of a special type of class called a union. The practical catch with a union is that you need to carry around an additional information that identifies what type of data is stored in the union, so it can be extracted correctly.

There are a few constraints on unions. One of those constraints is that a C++ class type with non-trivial constructors, destructor, or assignment operator cannot be a member of a union (and nor can arrays of such objects). Unions can also not have base classes, nor be base classes.

Unions are the C solution. They work, but they do not provide type safety, so if you store a double, but try to get an int, then you won't get the desired value. This can be resolved by having another variable that stores the type of the value in the union. Then when your accessor tries to read an int it can check to make sure the union really does store an int.

Another solution is to have a base class pointer or reference. This requires a warper object, generally a template, that inherits from a generic object type. The disadvantage of this approach is that is is very verbose. You write a lot of code for something very simple.

The best solution may be to use a pre-written implementation such as Boost::Variant.

This is for a simulation purpose of a construction site. For ex. if there is a job named "removal" it can be given as number of pieces (in this case its an int) or in volume or area (in this case its double).