YeongJunKim / issue

footprint of fixed error & some tips.
0 stars 0 forks source link

[C++] enum class 안에 method를 추가하고싶지만? 다른 방식으로 해결해보자 #25

Open YeongJunKim opened 2 years ago

YeongJunKim commented 2 years ago

https://stackoverflow.com/questions/21295935/can-a-c-enum-class-have-methods

explicit 키워드는 자신이 원하지 않는 형변환이 일어나지 않도록 제한하는 키워드이다.

constexpr 키워드는 컴파일 시간 상수를 만든다. 컴파일 시간에 결정되는 상수 값으로만 초기화 할 수 있다.

const와 constexpr의 주요 차이점은 const 변수의 초기화를 런타임까지 지연시킬 수 있는 반면, constexpr 변수는 반드시 컴파일 타임에 초기화가 되어 있어야 한다. 초기화가 안 되었거나, 상수가 아닌 값으로 초기화 시도시 컴파일이 되지 않는다.

함수에서 사용할때 inline을 암시한다. 즉, 컴파일 타임에 평가하기 때문이며, inline함수들과 같이 컴파일된다.

class Fruit
{
public:
  enum Value : uint8_t
  {
    Apple,
    Pear,
    Banana,
    Strawberry
  };

  Fruit() = default;
  constexpr Fruit(Value aFruit) : value(aFruit) { }

#if Enable switch(fruit) use case:
  // Allow switch and comparisons.
  constexpr operator Value() const { return value; }

  // Prevent usage: if(fruit)
  explicit operator bool() const = delete;        
#else
  constexpr bool operator==(Fruit a) const { return value == a.value; }
  constexpr bool operator!=(Fruit a) const { return value != a.value; }
#endif

  constexpr bool IsYellow() const { return value == Banana; }

private:
  Value value;
};

Now you can write:

Fruit f = Fruit::Strawberry;
f.IsYellow();

And the compiler will prevent things like:

Fruit f = 1;  // Compile time error.

You could easily add methods such that:

Fruit f("Apple");

and

f.ToString();