8
我試圖實現一個enum class
,其行爲與引入的行爲類似於具有類型安全等等的,但它也表現爲一個真實的類(帶有構造函數,方法等)。爲了做到這一點,我不停的內部enum
匿名:這有副作用,就是爲了保持m_value
作爲private
成員變量,我不得不添加一個名爲_
一個static
成員變量,你可以看到如下:如何在C++中實現一個真正的枚舉類
#include <iostream>
#include <experimental/string_view>
class State
{
public:
static enum
{
UNKNOWN,
STARTED,
STOPPED
} _;
private:
using Type = decltype(_);
Type m_value;
public:
constexpr State(Type value = UNKNOWN)
: m_value(value)
{ }
constexpr bool operator==(Type value) const
{
return m_value == value;
}
constexpr std::experimental::string_view to_string() const
{
switch (m_value)
{
case UNKNOWN: return "UNKNOWN";
case STARTED: return "STARTED";
case STOPPED: return "STOPPED";
}
return "";
}
};
State::Type State::_;
int main()
{
State state;
std::cout << state.to_string() << std::endl;
state = State::STARTED;
std::cout << state.to_string() << std::endl;
if(state == State::STOPPED)
{
std::cout << state.to_string() << std::endl;
}
return 0;
}
有沒有辦法擺脫無用的static
成員變量_
?我想保持內部enum
匿名,並以某種方式在需要時(=僅私人)獲取其類型。
另見:https://stackoverflow.com/questions/28828957/enum-to-string-in-modern-c11-c14-and-future-c17-c20 – Alex
你有沒有考慮過使用免費功能呢? – Yakk