C++代码书写模板 -- 如何判断函数类型

先说一个简单的方案. 经过验证 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. }

 

 

转载于:https://www.cnblogs.com/xujie2013/p/3425371.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值