您的位置:首页 > 其它

【练习】判断类中是否包含一个受保护的静态整形常量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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: