coderall/blogs

模板函数实例化与静态变量使用

Opened this issue · 0 comments

#include
using namespace std;
struct TypeCounter{
static int n_count;
};

int TypeCounter::n_count = 0;

template
int ComponentType()
{
static int componentID = TypeCounter::n_count++;
return componentID;
}

int main(int argc,char * argv[])
{
cout<<ComponentType< char >()<<endl;
cout<<ComponentType< int >()<<endl;
cout<<ComponentType< int >()<<endl;
cout<<ComponentType< double >()<<endl;
return 0;
}
上面程序的运行结果是什么呢?
这个例子很好的展示了模板函数实例化概念与静态变量的使用,可以当做编程技巧,即按照类型来生成唯一ID

这个编辑器不能很好的支持C++代码中模板的使用,在< >符号里面添加了空格,方便展示