给定下面的代码,我发现模板类的静态成员的初始化始终在通用全局变量后面,不是吗?我在哪里可以参考?
#include <stdio.h>
template<typename T>
class template_class
{
public:
template_class()
{
v = "not initialized!";
printf("template_class construct\n");
}
static T init_v()
{
printf("template_class::init_v called\n");
return "initialized";
}
static T v;
};
template<typename T> T template_class<T>::v = init_v();
template<typename T> T get_v()
{
printf("get_v called\n");
template_class<T> x;
return x.v;
}
const char *global = get_v<const char*>();
int main()
{
printf("global:%s\nnow:%s\n", global,
template_class<const char*>::v);
return 0;
}
vs2008、2015、2017和gcc-4.8.5编译的输出:
get_v called
template_class construct
template_class::init_v called
global:not initialized!
now:initialized