C ++“Floating Point Enum” [英] C++ "Floating Point Enum"

查看:168
本文介绍了C ++“Floating Point Enum”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个解决方案使用C ++ 03标准(我被限制使用这个版本的标准几年了)。欢迎使用C ++ 11的解决方案,但不会被接受作为此问题的答案。

I am looking for a solution using the C++03 standard (I am constrained to using this version of the standard for several years yet). Solutions for C++11 are also welcome, but will not be "accepted" as the answer to this question.

什么是简单,我可以将一组相关的常量浮点值表示为单一类型(类似于枚举),以确保类型安全性,而不会产生大量开销,并仍然允许我对这些值直接操作为浮点值。

What is a simple, concise way that I can represent a set of related constant floating point values as a single type (similar to an enum) to ensure type-safety without incurring significant overhead and still allow me to operate on the values as floats directly?

最后的结果是我想要做如下事情:

The end result is that I would like to be able to do something like the following:

enum FloatingPointEnum
{
   VALUE1 = 0.1234f,
   ...
   VALUEN = 0.6789f
};


float SomeFunction(FloatingPointEnum value)
{
    float new_value;
    /* perform some operation using "value" to calculate "new_value" */
    new_value = static_cast<float>(value); // <- a simplistic example
    return new_value;
}

虽然我可以想到几个解决方案, /直接的,因为我想,我想,有人必须已经有一个优雅的解决这个问题(但我似乎找不到一个在我的搜索)。

While I can think of several solutions, none of them are as clean/simple/straightforward as I would like and I figure that someone must already have an elegant solution to this problem (yet I cannot seem to find one in my searching).

EDIT:

我想对SomeFunction调用一个值,该值不直接指定为枚举类型的值,

I would like the following call to SomeFunction with a value that is not specified directly as a value from the enumerated type to fail to compile:

float nonEnumeratedValue = 5.0f
SomeFunction(nonEnumeratedValue);


推荐答案


这个问题的优雅解决方案

someone must already have an elegant solution to this problem

有很多问题没有优雅的解决方案(和许多没有解决方案)。什么让你认为这个问题有一个?这个假设是非常错误的。你最接近的是使用包装类。

There are lots of problems that have no elegant solution (and many that have no solution at all). What makes you think this problem has one? This assumption is very faulty. The closest you can get is to use a wrapper class.

class FloatingPointEnum {
    float f;
    FloatingPointEnum(float arg) : f(arg) {}
public:
    static const FloatingPointEnum Value1;
    static const FloatingPointEnum Value2;
    operator float() const { return f; }
};
const FloatingPointEnum FloatingPointEnum::Value1(0.1234f);
const FloatingPointEnum FloatingPointEnum::Value2(0.6789f);

这篇关于C ++“Floating Point Enum”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆