static_assert会做什么,你会用它做什么? [英] What does static_assert do, and what would you use it for?
问题描述
你能举一个例子, static_assert(...)'C ++ 0x'
会优雅地解决这个问题吗?
Could you give an example where static_assert(...) 'C++0x'
would solve the problem in hand elegantly?
我熟悉运行时 assert(...)
。什么时候应该优先于 static_assert(...)
比常规 assert(...)
?
I am familiar with run-time assert(...)
. When should I prefer static_assert(...)
over regular assert(...)
?
此外,在 boost
中有一些名为 BOOST_STATIC_ASSERT
的东西, static_assert(...)
?
Also, in boost
there is something called BOOST_STATIC_ASSERT
, is it the same as static_assert(...)
?
推荐答案
我的头...
#include "SomeLibrary.h"
static_assert(SomeLibrary::Version > 2,
"Old versions of SomeLibrary are missing the foo functionality. Cannot proceed!");
class UsingSomeLibrary {
// ...
};
假设 SomeLibrary :: Version
作为一个静态const,而不是 #define
d(如在C ++库中所期望的那样)。
Assuming that SomeLibrary::Version
is declared as a static const, rather than being #define
d (as one would expect in a C++ library).
与必须实际编译 SomeLibrary
和你的代码,链接一切,并运行可执行文件只有然后对比,以确定你花了30分钟编译不适用的版本 SomeLibrary
。
Contrast with having to actually compile SomeLibrary
and your code, link everything, and run the executable only then to find out that you spent 30 minutes compiling an incompatible version of SomeLibrary
.
@Arak,回应您的意见:是的,您可以有 static_assert
只是坐在那里,从它的外观:
@Arak, in response to your comment: yes, you can have static_assert
just sitting out wherever, from the look of it:
class Foo
{
public:
static const int bar = 3;
};
static_assert(Foo::bar > 4, "Foo::bar is too small :(");
int main()
{
return Foo::bar;
}
$ g++ --std=c++0x a.cpp
a.cpp:7: error: static assertion failed: "Foo::bar is too small :("
这篇关于static_assert会做什么,你会用它做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!