user63898
user63898

Reputation: 30915

How to make global type for all types of integer value types and to know their types in C++

I like to make function which get by reference variable from any integer (float , int , double ..) to as custom type . This type should know which type it was constructed from. For example, say I build my custom type

class Variable
{
   public:
      Variable(int &v)
      Variable(float &v)
      Variable(double &v)
      Variable(short &v)

      void setNuwValue(int &v)
      void setNuwValue(float &v)
      void setNuwValue(double &v)
      void setNuwValue(short &v)

       var_type_enum getType();
};

Now in my app I have function which takes this Variable type as an argument

void modifyVar(Variable& var)
{
   //1.how to know the var type it can return enum of types or string what ever ..
    var_type_enum type  = var.getType();
    var.setNuwValue(3);  
}

As you you can see this is only pseudo code without the implementation which I don't know how to implement and I need help. In short I want to be able to implement global type var as used in for example javascript "var" type

Upvotes: 2

Views: 94

Answers (2)

Glapa
Glapa

Reputation: 800

Try with this:

enum VT
{
  VT_int,
  VT_float,
  VT_double,
  VT_short
}

class Variable
{

  int i;
  float f;
  double d;
  short s;

  VT type;
public:
  Variable() : i(0), f(0), d(0), s(0) {}
  Variable(int &v) { i = v; type = VT_int; }
  Variable(float &v) { f = v; type = VT_float; }
  Variable(double &v) { d = v; type = VT_double; }
  Variable(short &v) { s = v; type = VT_short; }

  void setNuwValue(int &v) { i = v; type = VT_int; }
  void setNuwValue(float &v) { f = v; type = VT_float; }
  void setNuwValue(double &v) { d = v; type = VT_double; }
  void setNuwValue(short &v) { s = v; type = VT_short; }

  VT getType() const { return type; }
};

Upvotes: 2

MNS
MNS

Reputation: 1394

Probably you can make use of templates as shown below.

template<typename T> class Variable
{
public:

    const char* getType()
    {
        return typeid(T).name();
    }
    void setNuwValue( const T& ValueIn )
    {
        m_Value = ValueIn;
    }

private:

    T m_Value;
};

template<typename T>
void modifyVar(Variable<T>& var)
{
    const char* type = var.getType();
    var.setNuwValue(3);  
}

Below example call will return "double" when getType() is called.

Variable<double>Var;
modifyVar( Var );

Upvotes: 0

Related Questions