Compare typedef is same type

后端 未结 3 1181
情歌与酒
情歌与酒 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::value.

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

    template
    struct is_same 
    {
        static const bool value = false; 
    };
    
    template
    struct is_same  //specialization
    { 
       static const bool value = true; 
    };
    

    Done!

    Likewise you can implement static_assert1 as:

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

    Now you can use them as:

    static_assert::value>(); //pass
    static_assert::value>(); //fail
    

    Or you could wrap this in a macro as:

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

    then use as:

    STATIC_ASSERT(is_same::value); //pass
    STATIC_ASSERT(is_same::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.

提交回复
热议问题