Chinaunix
标题:
[结贴]C++能否知道一个模板类被特化了多少次?
[打印本页]
作者:
sentto2
时间:
2015-04-12 13:16
标题:
[结贴]C++能否知道一个模板类被特化了多少次?
本帖最后由 sentto2 于 2015-04-13 12:46 编辑
我在想一个技术问题----模板代码能否探测到自身被特化了多少次?
不能直接用搜代码的方式准确的知道一个模板被特化了多少次:
因为,模板可以被特化,或者被继承类偏特化。如果有复杂的模板继承关系的话,那么特化的次数是可能一个指数。
所以我想请教各位高手,假设我希望写下面的一段代码:
template<class T>
class Hello
{
//加入了某些代码,以及变量int i;
...
}
int main()
{
//我有很多特化Hello模板类及其继承类的代码
Hello<int> ...
Hello<ABC> ...
cout<<i<<endl;//这个i打印出Hello被特化了多少次.
return 0;
}
复制代码
如果i不在Hello这个模板类里面声明,在其他地方存在也可以。总之,我的需求就是:c++程序本身是否有能力知道,某个模板被特化了多少次,并且程序本身打印出来?
不知道模板元编程之类的技术是不是能做到?
谢谢。
作者:
cokeboL
时间:
2015-04-12 14:35
本帖最后由 cokeboL 于 2015-04-12 14:42 编辑
#include <iostream>
#include <stdio.h>
#include <map>
#include <string>
#define TEST_TYPE_COUNT 1
#if TEST_TYPE_COUNT
static std::map<std::string, bool> typeMap;
template<class T>
class Base
{
public:
Base()
{
typeMap[typeid(T).name()] = true;
//std::cout << typeid(T).name() << std::endl;
}
private:
static T _instance; //static Base _instance; static Base<T> _instance;
};
#endif
template<class T>
#if TEST_TYPE_COUNT
class Hello: public Base<T>
#else
class Hello:
#endif
{
};
int main()
{
Hello<int> hi;
Hello<std::string> hs;
#if TEST_TYPE_COUNT
std::cout << "T count: " << typeMap.size() << std::endl;
#endif
return 0;
}
复制代码
作者:
cokeboL
时间:
2015-04-12 15:11
本帖最后由 cokeboL 于 2015-04-12 15:13 编辑
#include <iostream>
#include <stdio.h>
#include <map>
#include <string>
#define TEST_TYPE_COUNT 1
#ifdef TEST_TYPE_COUNT 1
static std::map<std::string, bool> typeMap;
#endif
template<class T>
class Hello
{
public:
Hello ()
{
#ifdef TEST_TYPE_COUNT 1
typeMap[typeid(Hello<T>).name()] = true;
#endif
}
private:
#if TEST_TYPE_COUNT
static const Hello<T> _instance;
#endif
};
int main()
{
Hello<int> hi;
Hello<std::string> hs;
#if TEST_TYPE_COUNT
for(auto it = typeMap.begin(); it != typeMap.end(); it++)
{
std::cout << it->first << std::endl;
}
std::cout << "T count: " << typeMap.size() << std::endl;
#endif
return 0;
}
复制代码
怎么方便看楼主了
作者:
sentto2
时间:
2015-04-12 20:55
cokeboL 发表于 2015-04-12 15:11
怎么方便看楼主了
谢谢你的这个例子,但是我感觉static const Hello<T> _instance;这句是多余的,去掉好像也可以啊?
还是我理解有误?
作者:
cokeboL
时间:
2015-04-13 11:27
回复
4#
sentto2
恩,对的
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2