winston 发表于 2012-2-22 15:38:59

VC10和C++ 0x (3) - static_assert

static_assert断言(assertion)是提高代码质量的有效武器。C++标准库中的assert, MFC中的ASSERT宏\VERIFY宏都是断言的例子,它们的共同点是在运行时对程序状态进行判断,例如检查函数的参数有效性,检查类的不变式(invariant)等。而C++ 0x中的静态断言呢,和运行时的断言不一样,它是编译时执行检查的。看下面的例子:
// file: staticfluffykitten.cpptemplate <int N> struct Kitten {static_assert(N < 2, "Kitten<N> requires N < 2.");};int main() {    Kitten<1> peppermint;    Kitten<3> jazz;}
编译结果:staticfluffykitten.cpp(2) : error C2338: Kitten<N> requires N < 2.      staticfluffykitten.cpp(8) : see reference to class template instantiation 'Kitten<N>' being compiled      with      [            N=3上面例子中用static_assert对模板参数N进行了检查,如果断言失败编译器将使用用户自定义的错误消息。熟悉boost库的朋友对static_assert应该很熟悉 - boost提供了BOOST_STATIC_ASSERT宏跟C++ 0x中的static_assert类似,但是BOOST_STATIC_ASSERT没有使用用户自定义的错误消息。如果BOOST_STATIC_ASSERT失败,编译时会出现类似下面的错误:Error: use of undefined type 'boost::STATIC_ASSERTION_FAILURE<false>'
关于boost中的静态断言,参考boost的文档:http://www.boost.org/doc/libs/1_40_0/doc/html/boost_staticassert.htmlTechnorati Tags: C++,C++ 0x,boost,static_assert,boost.StaticAssert,BOOST_STATIC_ASSERT

页: [1]
查看完整版本: VC10和C++ 0x (3) - static_assert