Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

c++ - Compare typedef is same type

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...