编译时如何测试常量是否适合类型? [英] How to test if a constant fits into a type while compiling?

查看:21
本文介绍了编译时如何测试常量是否适合类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将编译时断言添加到以下 C++ 代码中(使用 Visual C++ 9 编译):

I'd like to add compile time asserts into the following C++ code (compiled with Visual C++ 9):

//assumes typedef unsigned char BYTE;
int value = ...;
// Does it fit into BYTE?
if( 0 <= value && value <= UCHAR_MAX ) {
    BYTE asByte = static_cast<BYTE>( value );
    //proceed with byte
} else {
    //proceed with greater values
}

问题是 UCHAR_MAXBYTE 是独立的 typedef 并且当这些代码被移植时,它们可能会不同步并且代码会中断.所以我想做这样的事情:

The problem is UCHAR_MAX and BYTE are independent typedefs and when this code is ported it can happen that they get out of sync and code will break. So I wanted to do something like this:

compileTimeAssert( sizeof( BYTE ) == sizeof( UCHAR_MAX ) );

但是 VC++9 在编译时产生负下标"错误 - sizeof( UCHAR_MAX ) 恰好是 4,而不是 1.

but VC++9 produces "negative subscript" error while compiling that - sizeof( UCHAR_MAX ) happens to be 4, not 1.

如何实现我想要的编译时检查?

How can I achieve the compile-time check I want?

推荐答案

你可以在编译时测试 assert ( (1 << (sizeof(BYTE)*CHAR_BIT)) - 1 ) == UCHAR_MAX.

You can test in the compile-time assert that ( (1 << (sizeof(BYTE)*CHAR_BIT)) - 1 ) == UCHAR_MAX.

(我假设您不是在问如何进行静态断言 - 有多种方法,请参阅 这里)

(I assume that you're not asking how to do a static assert - there are several ways, see here)

这篇关于编译时如何测试常量是否适合类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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