10
9

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 5 years have passed since last update.

ENUMとINTへの変換(列挙型をうまくつかってインデックスにする)

Last updated at Posted at 2014-08-17

いわゆるETOI,ITOE系の説明。

ETOIはEnum to Int

ITOEはInt to Enumです。

cpp
	// 自分のタイプに合わせてゲームのモードを選択する。
	enum struct type{
		OTTORI,
		SEKKACHI
	}

	const char* gamemodes[]={
		"スコアモード",	
		"タイムトライアルモード"
	}

// ※ enum structはC++11で追加されました。
// enum structはenum classと等価であり、従来の型の内enumとは違って
// 型があるものです。

こんな二つの情報があって、関連させたい場合、
enumを綺麗にintにキャストしてあげなければなりません。

★キャストについて★
enumのまま数字にキャストするには、
static_castを用います。static_castは、その場でキャスト可能かどうかを確認するので
ダメな場合はコンパイルエラーを吐きます。これに対して実行時に確認するものは
dynamic_castをもちいます。ダウンキャストに用います。
cocos2d-xでは、Ref*Node*とかに用いるといいです。(Node*)でのキャストはおすすめせず、

dynamic_cast<Node*>(hoge)

にしましょう。

少し話がそれました。enumをIntにキャストするので、

	type t = type::OTTORI;
	int index = static_cast<int>(t);

	const char* gamemode = gamemode[index];
// gamemode = gamemodes[0]

のように使います。

逆にindexからenumに戻したい場合は

 type t = static_cast<type>(index);

の用に用います。とりあえず頻繁にCの()でのキャストは脱却して、この二つから使ってみましょう。castにはreinterpret_castなど、いくつかありますが、頻用するのはこの2つだと思います。

10
9
1

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
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?