2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

古代C++でenum classを使いたかったある冒険者の日記

Last updated at Posted at 2022-09-28

C++03でenum classっぽい物を使いたかった備忘録です

ネタバレ

classかnamespaceで囲ってしまう

//class,structでも良い
namespace Type{
enum t{
    kHoge,
    kFuga
};
}
typedef Type::t Type_t;

序章. 冒険の始まり

止むに止まれぬ色々な事情で
2022年の昨今もC++03はバリバリ現役である。1

C++03にはscoped enumが無いので
ヘッダ等で安直な名前を使うと、衝突する恐れがある。

#ifndef HOGE_H
#define HOGE_H
enum Type{
    kOk //衝突の可能性あり
};
#endif

回避方法として、ユニークな接頭辞を付ける手がある。

enum Type{
    kHogeTypeOk
};

しかし、個人的には
無駄な情報をenum値に付け加えたくない。

解消法第一話 ラッパクラスで囲ってしまう

最初に思いついたのは、クラスでラップしてしまう方法

#include <iostream>

class Type {
 public:
  enum t {
    kHoge,
    kFuga,
  };

 private:
  t enum_value;

 public:
  Type(t enum_value) : enum_value(enum_value) {}
  Type(const Type& type) : enum_value(type.enum_value) {}
  virtual ~Type() {}
  Type& operator=(t enum_value) {
    this->enum_value = enum_value;
    return *this;
  }
  operator t() { return enum_value; }
};

int main() {
  Type t = Type::kFuga;
  Type t2 = t;
  Type t3(t);
  t2 = Type::kHoge;
  std::cout << t << "," << t2 << "," << t3 << std::endl;
}

enum classっぽく書けるけど
enumが増える度にこれ書くのはつらい
ソース読むのも時間かかる

解消法第二話 代替方法の思いつき

でどーするかと考えていたが

要はenum classの名の通り、enumへscope指定できれば良いだけなので
classなりnamespaceなりで囲った後
typedefすれば良いだけだと気づいた。

#include <iostream>

namespace Type{
enum t{
    kHoge,
    kFuga
};
}
typedef Type::t Type_t;

int main() {
  Type_t t = Type::kFuga;
  Type_t t2 = t;
  Type_t t3(t);
  t2 = Type::kHoge;
  std::cout << t << "," << t2 << "," << t3 << std::endl;
}

_t付けるのがやや面倒だけど
シンプルにenumへスコープ指定出来る。

終話

もっといい方法あったら教えてください
あと誰かぼくにC++20をください

  1. 個人の感想です。感想で終わってほしい。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?