简体   繁体   English

C ++中的编译时断言?

[英]Compile-time assertions in C++?

I recently came upon the need to have compile-time assertions in C++ to check that the sizes of two types were equal. 我最近发现需要在C ++中使用编译时断言来检查两种类型的大小是否相等。

I found the following macro on the web (stated to have come from the Linux kernel): 我在网上发现了以下宏(声称来自Linux内核):

#define X_ASSERT(condition) ((void)sizeof(char[1 - 2*!!(condition)]))

which I used like so: 我喜欢这样:

X_ASSERT(sizeof(Botan::byte) != sizeof(char));

This gets me curious - although this works , is there a cleaner way to do so? 这让我好奇-虽然这工作的 ,是有一个更清洁的方式来做到这一点? (obviously there's more than one way, as it is) Are there advantages or disadvantages to certain methods? (显然,不止一种方式)某些方法有优缺点吗?

In C++0x, there is a new language feature, static_assert , which provides a standard way to generate compile-time assertions. 在C ++ 0x中,有一个新的语言特性static_assert ,它提供了生成编译时断言的标准方法。 For example, 例如,

static_assert(sizeof(Botan::byte) != 1, "byte type has wrong size");

Visual C++ 2010 supports static_assert , as do g++ 4.3 (and greater) and Intel C++ 11.0. Visual C ++ 2010支持static_assert ,g ++ 4.3(及更高版本)和Intel C ++ 11.0也是如此。

You might want to take a look at Boost StaticAssert . 您可能想看看Boost StaticAssert The internals aren't exactly clean (or weren't the last time I looked) but at least it's much more recognizable, so most people know what it means. 内部不完全干净(或者不是我最后一次看)但至少它更容易被识别,因此大多数人都知道这意味着什么。 It also goes to some pains to produce more meaningful error messages if memory serves. 如果内存服务,它也会产生更有意义的错误消息。

Some other interesting options are here: http://www.jaggersoft.com/pubs/CVu11_3.html 其他一些有趣的选项在这里: http//www.jaggersoft.com/pubs/CVu11_3.html

Neat reading as the author walks the C (not C++) spec looking for syntax that can be leveraged as compile-time assertions. 作者在阅读C(非C ++)规范时寻找可以用作编译时断言的语法。

To do it right you need a C++0x friendly compiler, see James McNellis' and Jerry Coffins answers. 要做到正确,你需要一个C ++ 0x友好编译器,请参阅James McNellis和Jerry Coffins的答案。

You can't do much with the 1998 or 2003 C++ standards. 你不能对1998或2003 C ++标准做很多事情。 Take a look at these links for examples: 看一下这些链接的例子:

http://en.wikipedia.org/wiki/Assertion_(computing)#Static_assertions http://ksvanhorn.com/Articles/ctassert.html http://en.wikipedia.org/wiki/Assertion_(computing)#Static_assertions http://ksvanhorn.com/Articles/ctassert.html

有一个很好的#error预处理程序指令(请参阅这里有一篇关于它的好文章),但我认为它需要在#if ,而不是像在你的示例中那样用于“独立”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM