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;
    }

  • 相关阅读:
    委托
    SQL Server 2012 学习笔记5
    SQL Server 2012 学习笔记4
    SQL Server 2012 学习笔记3 增查改删
    SQL Server 2012 学习笔记2
    SQL Server 2012 学习笔记1
    PCD文件去除曲率的脚本
    pcl曲面网格模型的三种显示方式
    pcl计算样点法向并显示
    Markdown的使用---现学现用
  • 原文地址:https://www.cnblogs.com/zhoug2020/p/3940374.html
Copyright © 2011-2022 走看看