是否可以在C ++中使用编译时断言 [英] Is it possible to use compile time asserts in C++
问题描述
我想使用模板进行一些数据处理,但是我需要的代码在移植时或多或少的安全。
I want to use a template for some data processing, but I need the code to be more or less safe when ported.
这可能是一个问题,如果大小的变量增长超过预期值,所以我想在编译时断言一些假设仍然有效。
This might be a problem if sizes of variables grow beyond anticipated values, so I would like to assert at compile time that some assumptions are still valid.
例如, sizeof )> sizeof(int)
,所以如果这个假设失败,我可以打破构建。
For example, sizeof(long)>sizeof(int)
, so that if this assumption fails, I could break the build.
我知道, code> long> = int ,但这只是一个例子,不要专注于变量类型。
I know that standard mandates that long>=int
, but this is just an example, don't concentrate on the variable types.
推荐答案
C ++ 11有 static_assert
:
static_assert(sizeof(long) > sizeof(int), "long must be greater than int");
在旧版本的编译器上,您可以使用 Boost.StaticAssert 。
On older compilers you can use Boost.StaticAssert.
BOOST_STATIC_ASSERT(sizeof(long) > sizeof(int));
这篇关于是否可以在C ++中使用编译时断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!