由于我工作的公司禁止使用 boost,因此我需要用纯 C++ 实现其功能.我已经研究了 boost 源,但它们似乎太复杂而无法理解,至少对我来说是这样.我知道 C++0x 标准中有一种叫做 static_assert()
的东西,但我不想使用任何 C++0x 特性.
Since boost is forbidden in a company I work for I need to implement its functionality in pure C++. I've looked into boost sources but they seem to be too complex to understand, at least for me. I know there is something called static_assert()
in the C++0x standart, but I'd like not to use any C++0x features.
另一个技巧(可以在 C 中使用)是在断言失败时尝试构建一个大小为负的数组:
One other trick (which can be used in C) is to try to build an array with a negative size if the assert fail:
#define ASSERT(cond) int foo[(cond) ? 1 : -1]
作为奖励,您可以使用 typedef 而不是对象,这样它就可以在更多上下文中使用并且在成功时不会发生:
as a bonus, you may use a typedef instead of an object, so that it is usable in more contexts and doesn't takes place when it succeed:
#define ASSERT(cond) typedef int foo[(cond) ? 1 : -1]
最后,构建一个名称冲突可能性较小的名称(并且至少可以在不同的行中重复使用):
finally, build a name with less chance of name clash (and reusable at least in different lines):
#define CAT_(a, b) a ## b
#define CAT(a, b) CAT_(a, b)
#define ASSERT(cond) typedef int CAT(AsSeRt, __LINE__)[(cond) ? 1 : -1]
这篇关于BOOST_STATIC_ASSERT 没有提升的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!