次のようなものに要約できるクラスがある場合:
// test.hpp
class Test{
public:
template<typename T> static T value;
};
template<typename T> Test::value = {};
value
このクラスは、1 つの .cpp ファイルでインスタンス化されたものだけを検索するときに使用できます。しかし、これを複数の .cpp ファイルで使用しようとすると、既に定義されているリンカー エラーが発生します。
//somefile1.cpp
include "test.hpp"
void fn(){
int i = Test::value<int>;
}
// somefile2.cpp
include "test.hpp"
void otherfn(){
// public static int value already defined in somefile1.obj
int j = Test::value<int>;
}
template<typename T> Test::value = {}
独自の .cpp ファイルに配置すると、すべての使用で未解決の外部エラーが発生します。どうしたの?