類模板內的static成員變量是在需要用的時候纔會去調用類外初始化,否則實例化子類後,直接調用b的成員函數等時,會報錯undefined reference
#include <iostream>
using namespace std;
template <typename T>
class CTest {
public:
class B {
public:
B()
{
cout << "construct B" << endl;
}
};
private:
static B b;
// 此成員函數作用是構造子類調用b,從而使b在一開始就初始化
virtual void* touch(){return &b;}
};
template<typename T>
typename CTest<T>::B CTest<T>::b;
class A : public CTest<A> {
public:
static void func()
{
}
};
template<>
CTest<A>::B CTest<A>::b{};
int main()
{
cout << "main" << endl;
return 0;
}