LoginSignup
5
3

More than 5 years have passed since last update.

[C++]任意のタイミングで初期化できるstatic constメンバ変数もどき

Posted at

DXライブラリを使っているわけですが、
白色を取得するために毎回
Dxlib::GetColor( 255, 255, 255 );
と書いていてはめんどくさすぎる。

こう書きたかった

int hoge = Color::white;

これで動いて欲しかった

class Color {
public:
  static const int white = DxLib::GetColor( 255, 255, 255 );
}

宣言の見た目もさっぱりしてるし、呼び出しも綺麗。
しかしこれでは、whiteが初期化される前にDxLibの初期化が終わっていないようで、上記のように呼び出しても正しい値が帰ってこない。

こうしたら動いた

class Color {
public:
  static int white() {
    static int color = DxLib::GetColor( 255, 255, 255 );
    return color;
  }
};

そして
int hoge = Color::white();
と呼び出す。

こうすればColor::white()が最初に呼び出されたタイミングで値が初期化されるため、任意のタイミングでの初期化が可能になる。
熟練プログラマにとっては当たり前の話か・・・

(でもやっぱり関数内のstaticは気持ち悪くない?)

さらにこうした

#define DEFINE_COLOR( name, r, g, b ) \
  static int name() { \
    static int color = DxLib::GetColor( r, g, b ); \
    return color; \
  }

個人的にマクロはあんまり増やしたくないんだけど、これで宣言部もスッキリしました・・・

5
3
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
5
3