Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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've come up with the following solution myself.. is it safe? Thanks

template<typename T>
struct TypeTest
{
    static void Compare(const TypeTest& other) {}
};

typedef unsigned long long UINT64;
typedef unsigned long long UINT_64;
typedef unsigned int UINT_32;

int main()
{
    TypeTest<UINT64>::Compare(TypeTest<UINT64>()); // pass
    TypeTest<UINT64>::Compare(TypeTest<UINT_64>()); // pass
    TypeTest<UINT64>::Compare(TypeTest<UINT_32>()); // fail
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
480 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...