如何为所有类型的整数值类型创建全局类型,并在C++中了解它们的类型

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

本文关键字:类型 C++ 并在 了解 全局 整数 创建      更新时间:2023-10-16

我喜欢将通过引用从任何整数(float、int、double..)中获取变量的函数作为自定义类型。此类型应该知道它是从哪个类型构造的。例如,假设我构建自定义类型的

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();
};

现在在我的应用程序中,我有一个函数,它将此变量类型作为参数

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);  
}

正如你所看到的,这只是没有实现的伪代码,我不知道如何实现,我需要帮助。简而言之,我希望能够实现全局类型var,例如javascript"var"type

试试这个:

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; }
};

您可能可以使用如下所示的模板。

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);  
}

下面的示例调用将在调用getType()时返回"double"。

Variable<double>Var;
modifyVar( Var );