【练习】判断类中是否包含一个受保护的静态整形常量val
2015-04-02 11:46
423 查看
下面的代码在老的编译器上不work,我用gcc 4.8.2编译没问题
template <typename T> class is_class { typedef char YES; typedef int NO; template <typename U> static YES matcher(void (U::*)(void)); template <typename> static NO matcher(...); public: static const bool r = sizeof(matcher<T>(0)) == sizeof(YES); }; template <typename T> class is_public { typedef char YES; typedef int NO; template <typename U> static YES (&matcher(int))[1 + 0 * U::val]; template <typename> static NO matcher(...); public: static const bool r = sizeof(matcher<T>(0)) == sizeof(YES); }; template <typename T> class is_public_or_protected : private T { typedef char YES; typedef int NO; template <typename U> static YES (&matcher(int))[1 + 0 * is_public_or_protected<U>::val]; template <typename> static NO matcher(...); public: static const bool r = sizeof(matcher<T>(0)) == sizeof(YES); }; template <bool B, typename T> struct if_ { static const bool r = T::r; }; template <typename T> struct if_<false, T> { static const bool r = false; }; template <typename T> struct is_protected { static const bool r = if_< is_class<T>::r && !is_public<T>::r, is_public_or_protected<T> >::r; }; //test case #include <cstdio> static void test(bool r, const char * s) { printf("%-16s%s\n", r?"PASS":"FAILED", s); } #define TEST(x, b) test(is_protected<x>::r == b, #x) class int0 {}; class int1 { public: static const int val = 0; }; class int2 { protected: static const int val = 0; }; class int3 { private: static const int val = 0; }; template <typename T> class T1 : public T {}; template <typename T> class T2 : protected T {}; template <typename T> class T3 : private T {}; class int4 { protected: static const double val = 0; }; class int5 { protected: static const char val = 0; }; class int6 { protected: static const short val = 0; }; int main() { TEST(int, false); TEST(double, false); TEST(int0, false); TEST(int1, false); TEST(int2, true); TEST(int3, false); TEST(T1<int1>, false); TEST(T1<int2>, true); TEST(T1<int3>, false); TEST(T2<int1>, true); TEST(T2<int2>, true); TEST(T2<int3>, false); TEST(T3<int1>, false); TEST(T3<int2>, false); TEST(T3<int3>, false); TEST(int4, false); TEST(int5, true); TEST(int6, true); return 0; }
相关文章推荐
- 判断一个IP区间(或IP)是否被另一个IP区间所包含
- 判断一个字符串中是否包含某个字符
- php 如何判断一个常量是否已经定义
- 判断一个数组中是否包含某个字符串
- /判断一个字符串是否包含别一个字符串 1.
- 判断一个IP区间(或IP)是否被另一个IP区间所包含
- 判断字符串是否包含数字得一个小函数
- Array.BinarySearch判断一个字符串是否包含在一个字符数组中
- SQLSERVER 判断一个字符串是否包含特殊字符
- js判断一个元素是否包含另外一个元素
- 判断一个IP区间(或IP)是否被另一个IP区间所包含
- 判断一个char[]里是否包含两个连续的\r\n
- 判断一个IP区间(或IP)是否被另一个IP区间所包含
- 一个很有用的自定义函数(判断自然数是否包含2的指定次幂)
- php学习笔记 定义常量,包含文件,判断常量是否存在
- 判断一个dataset的数据是否包含另一个dataset的数据
- 判断一个字符是否包含在另一字符串中
- 判断一个字符串变量是否包含另一个子字符串
- 判断一个字符串是否包含另一个字符串(indexOf和正则表达式的比较)
- T.array.contains判断一个数组中是否包含给定元素