Chinaunix首页 | 论坛 | 博客
  • 博客访问: 339152
  • 博文数量: 88
  • 博客积分: 1695
  • 博客等级: 上尉
  • 技术积分: 1380
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-06 15:48
个人简介

喜欢美食, 旅行..

文章分类

全部博文(88)

文章存档

2014年(2)

2013年(12)

2012年(14)

2010年(8)

2009年(52)

我的朋友

分类: C/C++

2013-11-14 20:40:19

先说一个简单的方案. 经过验证 g++ 和 vs2010 都可以.
原理就是利用函数类型可以直接转换成函数指针.

  1. template<class T> bool test( T * t )
  2. {
  3.     return true;
  4. }
  5. bool test( ... )
  6. {
  7.     return false;
  8. }

  9. #include<iostream>
  10. using namespace std;
  11. int main()
  12. {
  13.     int k = 12;
  14.     cout << test(main) << endl;
  15.     cout << test( k ) << endl;

  16.     typedef int(*PtrFun)();
  17.     PtrFun ptr = main;
  18.     cout << test(ptr) << endl;
  19.     cout << test( 12 ) << endl;

  20.     return 0;
  21. }
再说一个稍微复杂点的方案. g++ 编译没问题. vs2010 编译不过去.
利用了函数类型没有数组的概念. 入梅不存在某个类型的数组, 0 转换 U (*)[1] 自然会失败
  1. template<class T>
  2. class IsFunction
  3. {
  4. private:
  5.     typedef char ONE;
  6.     typedef struct{char a[2];} TWO;
  7.     template<class U>static ONE test(...);
  8.     template<class U>static TWO test(U (*)[1]);
  9. public:
  10.     enum{YES = sizeof(IsFunction<T>::test<T>(0)) == 1 };
  11.     enum{NO = !YES};
  12. };

  13. template<>
  14. class IsFunction<T&>
  15. {
  16. public:
  17.     enum{YES = 0 };
  18.     enum{NO = !YES};
  19. }

  20. template<>
  21. class IsFunction<void>
  22. {
  23. public:
  24.     enum{YES = 0 };
  25.     enum{NO = !YES};
  26. }
  27. template<>
  28. class IsFunction<const void>
  29. {
  30. public:
  31.     enum{YES = 0 };
  32.     enum{NO = !YES};
  33. }

  34. template<class T>
  35. long kkk(T&){return IsFunction<T>::YES;}

  36. #include<iostream>
  37. using namespace std;

  38. int main()
  39. {
  40.     int k = 23;
  41.     cout << kkk(main) << endl;
  42.     cout << kkk(k) << endl;
  43.     cout << IsFunction<int>::YES << endl;
  44.     
  45.     typedef int(*PtrFun)();
  46.     PtrFun ptr = main;
  47.     cout << IsFunction<PtrFun>::YES << endl;
  48.     return 0;
  49. }


阅读(5322) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~