请看以下内容:
#include <string>
#include <unordered_map>
template <int N> class Object;
template <int N> class Thing;
template <int N>
class Factory {
private:
using FuncPtr = Object<N>*(*)(Thing<N>*);
static std::unordered_map<std::string, FuncPtr> map;
public:
static void insertInMap (const std::string& tag, FuncPtr funcPtr) {
map.emplace (tag, funcPtr);
}
};
template <int N>
std::unordered_map<std::string, typename Factory<N>::FuncPtr> Factory<N>::map;
// won't compile on GCC 4.8.1:
//template <> std::unordered_map<std::string, typename Factory<0>::FuncPtr> Factory<0>::map;
template <int N> struct Object {};
struct Blob : Object<0> {
static Blob prototype;
Blob() {Factory<0>::insertInMap ("Blob", Blob::create);}
Blob (Thing<0>*) {/* */}
static Object<0>* create (Thing<0>* x) {return new Blob(x);}
};
Blob Blob::prototype; // Calls up Factory<0>::insertInMap during compile time, but crashes when run.
int main()
{
}
所以看起来Blob Blob::prototype;
崩溃是因为Factory<0>::map
尚未实例化,所以我尝试用以下行实例化它:
template <> std::unordered_map<std::string, typename Factory<0>::FuncPtr> Factory<0>::map;
但它不会编译(使用 GCC 4.8.1):
C:\Users\Andy\AppData\Local\Temp\ccsGlFeV.o:Practice.cpp:(.text$_ZN7FactoryILi0E
E11insertInMapERKSsPFP6ObjectILi0EEP5ThingILi0EEE[__ZN7FactoryILi0EE11insertInMa
pERKSsPFP6ObjectILi0EEP5ThingILi0EEE]+0x14): undefined reference to `Factory<0>:
:map'
collect2.exe: error: ld returned 1 exit status