C++ でヘッダファイルだけでグローバル変数を定義する方法
今日、会社で出た話。C言語だとグローバル変数を (宣言ではなく) 定義するには、必ずソースファイル内を書かなければいけなくて面倒だけど、C++ なら簡単。テンプレートクラスを使えば、ヘッダファイルだけでグローバル変数を定義できる。以下、参考。
なので、テンプレートクラスのstaticメンバは異なる翻訳単位で複数回定義されて
cppll:8425 Re: クラステンプレートのstaticメンバ変数
いても、全く同じ定義ならば、一回しか定義されていないのと同義です。
具体的なコードとしては、以下のような感じ (picojson から一部変更して引用)。
template <typename AlwaysBool> struct last_error_t { static std::string s; }; template <typename AlwaysBool> std::string last_error_t<AlwaysBool>::s; inline void set_last_error(const std::string& s) { last_error_t<bool>::s = s; } inline const std::string& get_last_error() { return last_error_t<bool>::s; }