【问题标题】:Is there a way to create an enumerated data type for non integers?有没有办法为非整数创建枚举数据类型?
【发布时间】:2014-10-22 16:43:12
【问题描述】:

我正在编写一个简单的转换程序,我想创建类似的东西:

//Ratios of a meter
enum Unit_Type
{
  CENTIMETER = 0.01, //only integers allowed
  METER = 1,
  KILOMETER = 1000
};

是否有一个简单的数据结构可以让我像这样组织我的数据?

【问题讨论】:

  • 既然您已经在尝试编写可读程序(值得称赞),为什么不一直使用std::ratio 来获得无量纲比率,并使用单独的单位系统来获得维度?
  • @KerrekSB 别忘了Boost.Units
  • @Mario 抱歉复制/粘贴错误 :) 这是正确的:stackoverflow.com/questions/19408305/c-floating-point-enum
  • 你不能改变数字以厘米为底,即:CENTIMETER=1METER=100 和 `KILOMETER=100000'

标签: c++ data-structures types enumerated-types


【解决方案1】:

不是真的。虽然 C++11 引入了一些 really neat new things for enums,例如特别是能够为它们分配一些特定的内部数据类型(如char),无法添加浮点数或任何其他非整数类型。

根据您实际尝试执行的操作,我会为此使用一些普通的旧结构:

struct UnitInfo {
    const char *name;
    float       ratio;
};

UnitInfo units[] = {
    {"centimeter",   0.01f},
    {"meter",        1},
    {"kilometer", 1000},
    {0, 0} // special "terminator"
};

然后,您可以使用指针作为迭代器来迭代所有可用单元:

float in;
std::cout << "Length in meters: ";
std::cin >> in;

// Iterate over all available units
for (UnitInfo *p = units; *p; ++p) {
    // Use the unit information:
    //  p[0] is the unit name
    //  p[1] is the conversion ratio
    std::cout << (in / p[1]) << " " << p[0] << std::endl;
}

如果这是关于将这些比率与实际值一起使用(如 100 * CENTIMETER),那么 C++11 的 user-defined literals 可能适合您:

constexpr float operator"" _cm(float units) {
    return units * .01f;
}

然后可以这样使用:

float distance = 150_cm;

【讨论】:

    【解决方案2】:

    有没有简单的数据结构...

    不像您想用Unit_Type 做的那样简单。您当然可以创建一个 Units_Of_Distance 类和一些名为 centimetremetrekilometre 等的 const 实例 - 将您的数字传递给构造函数。

    如果您不想从头开始编写类似的东西,或者想要更强大的东西,Kerrek 和 Angew 的 cmets 是不错的选择......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      相关资源
      最近更新 更多