zoukankan      html  css  js  c++  java
  • 编译期间侦测可转换性

    template <class T,class U>
    class Conversion
    {
        typedef char Small;
        class Big {char dummy[2]; };
        static Small Test(U);
        static Big Test(...);
        static T MakeT(); //稻草人函数
    public:
        enum { exists = sizeof(Test(MakeT())) == sizeof(Small)};
    };

    int _tmain(int argc, _TCHAR* argv[])
    {
        using namespace std;

        cout<< Conversion<double,int>::exists << ' ';
        
        getchar();

        return 0;
    }

    sizeof 并不会真有任何表达式被求值。

    ====================================

    template <class T,class U>
    class Conversion
    {
        typedef char Small;
        class Big {char dummy[2]; };
        static Small Test(U);
        static Big Test(...);
        static T MakeT();
    public:
        enum { exists = sizeof(Test(MakeT())) == sizeof(Small)};
        enum { exists2way = exists &&
            Conversion<U,T>::exists };
        enum { sameType = false};
    };

    template <class T>
    class Conversion<T,T>
    {
    public:
        enum { exists = 1; exists2way =1; sameType = false};
    };

    class A
    {
        int a;
    };

    class B :public A
    {
        int a;
    };

    #define  SUPERSUBCLASS(T,U)
        (Conversion<const U*,const T*>::exists &&
        !Conversion<const T*,void *>::sameType)

    int _tmain(int argc, _TCHAR* argv[])
    {
        using namespace std;

        cout<< Conversion<double,int>::exists << ' ';

        if( SUPERSUBCLASS(A,B) )
        {
            cout<< "SUPERSUBCLASS<A,B>,A is base class" << ' ';
        }
        
        getchar();

        return 0;
    }

  • 相关阅读:
    verilog中的function用法与例子
    HDMI IP学习笔记
    include使用中注意的问题
    PCIE学习
    HDMI学习
    (转)modelsim10.0C编译ISE14.7的xilinx库(xilinx ip核)
    2014年七月华为校招机试题目--最难的一道, 呵呵!
    欧拉函数
    素数高效率筛选法
    树-二叉树的编号
  • 原文地址:https://www.cnblogs.com/zhoug2020/p/3940374.html
Copyright © 2011-2022 走看看