簡體   English   中英

C ++“浮點枚舉”

[英]C++ “Floating Point Enum”

我正在尋找使用C ++ 03標准的解決方案(我被限制使用這個版本的標准已有好幾年了)。 C ++ 11的解決方案也是受歡迎的,但不會被“接受”作為這個問題的答案。

什么是簡單,簡潔的方法,我可以將一組相關的常量浮點值表示為單一類型(類似於枚舉),以確保類型安全,而不會產生顯着的開銷,並且仍允許我直接對值進行操作?

最終的結果是我希望能夠做如下的事情:

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

雖然我可以想到幾個解決方案,但沒有一個像我想的那樣干凈/簡單/直接,我認為某人必須已經有一個優雅的解決方案來解決這個問題(但我似乎無法在我的搜索中找到一個)。

編輯:

我希望以下對SomeFunction的調用,其值不是直接指定為枚舉類型的值,無法編譯:

float nonEnumeratedValue = 5.0f
SomeFunction(nonEnumeratedValue);

某人必須已經有一個優雅的解決方案來解決這個問

有很多問題沒有優雅的解決方案(許多問題根本沒有解決方案)。 是什么讓你認為這個問題有一個? 這個假設非常錯誤。 你可以得到的最接近的是使用包裝類。

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 ++ 11中,您可以使用constexpr來實現您想要的功能。

constexpr - 指定變量或函數的值可以出現在常量表達式中

http://en.cppreference.com/w/cpp/language/constexpr

使用constexpr您可以定義編譯時常量。 這僅適用於文字類型,例如float 既然我們想要的話

float nonEnumeratedValue = 5.0f;
SomeFunction(nonEnumeratedValue);

失敗,我們不能使用簡單的typedef 相反,我們使用Boost的BOOST_STRONG_TYPEDEF

#include <boost/serialization/strong_typedef.hpp>

BOOST_STRONG_TYPEDEF(float, FloatingPointEnum);
constexpr float VALUE1 = 0.1234f;
constexpr float 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;
}

現在,您只能使用FloatingPointEnum實例調用該函數。 不幸的是,實例化語法不再那么好了

FloatingPointEnum f {VALUEN};

或者,您可以簡單地使用D編程語言,其中支持浮點枚舉,並且以下代碼按預期工作:

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


float SomeFunction(FloatingPointEnum value)
{
    float new_value;
    new_value = value; // No cast needed, welcome to D!
    return new_value;
}

使用float調用SomeFunction導致

Error: function test.SomeFunction (FloatingPointEnum value) is not callable using argument types (float)

一種可能的替代解決方案,並非總是適用但非常干凈,是使用固定精度。

讓我們假設你有一個包含一些距離的枚舉

enum DistancesMeter{
 A = 0.25,
 b = 0.05,
};

然后你可以簡單地切換到使用mm

enum DistancesMM{
 A = 250,
 b = 50,
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM