比较typedef是相同类型 [英] Compare typedef is same type

查看:156
本文介绍了比较typedef是相同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C ++(不是11)和使用一些库具有不同的typedefs整数数据类型。有什么办法,我可以断言两个typedef是相同的类型?我自己想出了以下解决方案..它是安全吗?
感谢

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
}


推荐答案

+11,您可以使用 std :: is_same< T,U> :: value

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

没有C ++ 11,你可以自己实现这个功能:

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

完成!

static_assert 1 as:

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

现在您可以使用它们:

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

然后使用:

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

如果使用宏,则会在编译器生成的消息中看到以下字符串if断言失败:

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.

希望有帮助。

1。注意,在C ++ 11中, static_assert 是一个操作符(在编译期操作),而不是类模板。在上面的代码中, static_assert 是一个类模板。

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.

这篇关于比较typedef是相同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆