constexprで文字列定数定義
はじめに
ある文字列の実態を定義したい場合はヘッダーファイル側(.hpp)で静的変数宣言し,
実装側(.cpp)に文字列の初期化を定義するのが普通ですが,
ヘッダーファイル側(.hpp)だけで文字列を定義するやり方について考えました
constexprを使う
constexprで修飾したメンバ変数はheader内で初期化宣言できます
(constexprが修飾子なのかは不明でものを言っています)
struct foo { static constexpr char* bar = "baz"; };
ただし,このままだとwarningが出る(g++4.8.1)
warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
これを黙らせる方法
#include <string> struct foo { static constexpr char* bar = (char*)"baz"; };
文字列リテラルからchar*
への型変換が[[deprecated]]
(非推奨)のため
warningが出る模様
文字列リテラルはconst char*
ということでしょう