Compare typedef is same type

后端 未结 3 1171
情歌与酒
情歌与酒 2020-12-17 23:25

I am using C++ (not 11) and using some libraries which have different typedefs for integer data types. Is there any way I can assert that two typedefs are the same type? I\'

相关标签:
3条回答
  • 2020-12-17 23:43

    In C++11, you could use std::is_same<T,U>::value.

    Since you don't have C++11, you could implement this functionality yourself as:

    template<typename T, typename U>
    struct is_same 
    {
        static const bool value = false; 
    };
    
    template<typename T>
    struct is_same<T,T>  //specialization
    { 
       static const bool value = true; 
    };
    

    Done!

    Likewise you can implement static_assert1 as:

    template<bool> struct static_assert;
    template<> struct static_assert<true> {};  //specialization
    

    Now you can use them as:

    static_assert<is_same<UINT64,UINT64>::value>(); //pass
    static_assert<is_same<UINT64,UINT32>::value>(); //fail
    

    Or you could wrap this in a macro as:

    #define STATIC_ASSERT(x)  { static_assert<x> static_assert_failed; (void) static_assert_failed; }
    

    then use as:

    STATIC_ASSERT(is_same<UINT64,UINT64>::value); //pass
    STATIC_ASSERT(is_same<UINT64,UINT32>::value); //pass
    

    If you use macro, then you would see the following string in the compiler generated message if the assert fails:

    static_assert_failed
    

    which is helpful. With the other information in the error message, you would be able to figure out why it failed.

    Hope that helps.


    1. Note that in C++11, static_assert is an operator (which operates at compile-time), not a class template. In the above code, static_assert is a class template.

    0 讨论(0)
  • 2020-12-17 23:46

    std::type_info might help you.

    0 讨论(0)
  • 2020-12-17 23:56

    Since you don't have C++11, use boost.

    BOOST_STATIC_ASSERT(boost::is_same<T, U>::value);
    

    You can write some kind of your assert function, instead of BOOST_STATIC_ASSERT.

    0 讨论(0)
提交回复
热议问题