Chinaunix

标题: [结贴]C++能否知道一个模板类被特化了多少次? [打印本页]

作者: sentto2    时间: 2015-04-12 13:16
标题: [结贴]C++能否知道一个模板类被特化了多少次?
本帖最后由 sentto2 于 2015-04-13 12:46 编辑

我在想一个技术问题----模板代码能否探测到自身被特化了多少次?

不能直接用搜代码的方式准确的知道一个模板被特化了多少次:
因为,模板可以被特化,或者被继承类偏特化。如果有复杂的模板继承关系的话,那么特化的次数是可能一个指数。

所以我想请教各位高手,假设我希望写下面的一段代码:

  1. template<class T>
  2. class Hello
  3. {
  4.    //加入了某些代码,以及变量int i;
  5. ...
  6. }

  7. int main()
  8. {
  9.    //我有很多特化Hello模板类及其继承类的代码
  10.    Hello<int> ...
  11.    Hello<ABC> ...

  12.    cout<<i<<endl;//这个i打印出Hello被特化了多少次.
  13.    return 0;
  14. }
复制代码
如果i不在Hello这个模板类里面声明,在其他地方存在也可以。总之,我的需求就是:c++程序本身是否有能力知道,某个模板被特化了多少次,并且程序本身打印出来?
不知道模板元编程之类的技术是不是能做到?

谢谢。
作者: cokeboL    时间: 2015-04-12 14:35
本帖最后由 cokeboL 于 2015-04-12 14:42 编辑
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <map>
  4. #include <string>

  5. #define TEST_TYPE_COUNT 1

  6. #if TEST_TYPE_COUNT
  7. static std::map<std::string, bool> typeMap;

  8. template<class T>
  9. class Base
  10. {
  11. public:
  12.         Base()
  13.         {
  14.                 typeMap[typeid(T).name()] = true;
  15.                 //std::cout << typeid(T).name() << std::endl;
  16.         }
  17. private:       
  18.         static T _instance; //static Base _instance; static Base<T> _instance;
  19. };
  20. #endif

  21. template<class T>
  22. #if TEST_TYPE_COUNT
  23. class Hello: public Base<T>
  24. #else
  25. class Hello:
  26. #endif
  27. {

  28. };

  29. int main()
  30. {
  31.     Hello<int> hi;
  32.     Hello<std::string> hs;

  33. #if TEST_TYPE_COUNT
  34.         std::cout << "T count: " << typeMap.size() << std::endl;
  35. #endif
  36.     return 0;
  37. }
复制代码

作者: cokeboL    时间: 2015-04-12 15:11
本帖最后由 cokeboL 于 2015-04-12 15:13 编辑
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <map>
  4. #include <string>

  5. #define TEST_TYPE_COUNT 1

  6. #ifdef TEST_TYPE_COUNT 1
  7. static std::map<std::string, bool> typeMap;
  8. #endif

  9. template<class T>
  10. class Hello
  11. {
  12. public:
  13.         Hello ()
  14.         {
  15. #ifdef TEST_TYPE_COUNT 1
  16.                 typeMap[typeid(Hello<T>).name()] = true;
  17. #endif
  18.         }

  19. private:
  20. #if TEST_TYPE_COUNT
  21.         static const Hello<T> _instance;
  22. #endif
  23. };

  24. int main()
  25. {
  26.     Hello<int> hi;
  27.     Hello<std::string> hs;

  28. #if TEST_TYPE_COUNT
  29.         for(auto it = typeMap.begin(); it != typeMap.end(); it++)
  30.         {
  31.                 std::cout << it->first << std::endl;
  32.         }
  33.         std::cout << "T count: " << typeMap.size() << std::endl;
  34. #endif
  35.     return 0;
  36. }
复制代码
怎么方便看楼主了
作者: 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