下面的代码在老的编译器上不work,我用gcc 4.8.2编译没问题
template
class is_class {
typedef char YES;
typedef int NO;
template static YES matcher(void (U::*)(void));
template static NO matcher(...);
public:
static const bool r = sizeof(matcher(0)) == sizeof(YES);
};
template
class is_public {
typedef char YES;
typedef int NO;
template static YES (&matcher(int))[1 + 0 * U::val];
template static NO matcher(...);
public:
static const bool r = sizeof(matcher(0)) == sizeof(YES);
};
template
class is_public_or_protected : private T {
typedef char YES;
typedef int NO;
template static YES (&matcher(int))[1 + 0 * is_public_or_protected::val];
template static NO matcher(...);
public:
static const bool r = sizeof(matcher(0)) == sizeof(YES);
};
template
struct if_ {
static const bool r = T::r;
};
template
struct if_ {
static const bool r = false;
};
template
struct is_protected {
static const bool r = if_::r && !is_public::r, is_public_or_protected >::r;
};
//test case
#include
static void test(bool r, const char * s) {
printf("%-16s%s\n", r?"PASS":"FAILED", s);
}
#define TEST(x, b) test(is_protected::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 class T1 : public T {};
template class T2 : protected T {};
template 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, false);
TEST(T1, true);
TEST(T1, false);
TEST(T2, true);
TEST(T2, true);
TEST(T2, false);
TEST(T3, false);
TEST(T3, false);
TEST(T3, false);
TEST(int4, false);
TEST(int5, true);
TEST(int6, true);
return 0;
}