boost之正确性和测试
BOOST_ASSERT在debug模式下有效。
#include <iostream>
#include <boost/assert.hpp>
using namespace std;
using namespace boost;
double fun(int x)
{
BOOST_ASSERT(x!=0 && "divede by zero");
return 1.0/x;
}
int main()
{
fun(0);
return 0;
}
获取更多的诊断信息:
#include <iostream>
#include <boost/assert.hpp>
#include <boost/format.hpp>
using namespace std;
using namespace boost;
#define BOOST_ENABLE_ASSERT_HANDLER
namespace boost
{
void assertion_failed(char const * exptr,char const *function,char const * file,long line)
{
boost::format fmt("Assertion failed!\n Expression: %s\n Function :%s\nFile %s\nLine:%ld\n\n");
fmt % exptr % function % file%line;
cout << fmt;
}
}
double fun(int x)
{
BOOST_ASSERT(x!=0 && "divede by zero");
return 1.0/x;
}
int main()
{
fun(0);
return 0;
}
静态断言,将错误转移到编译期内
#include <iostream>
#include <boost/static_assert.hpp>
using namespace std;
using namespace boost;
template<typename T>
T my_min(T a,T b)
{
BOOST_STATIC_ASSERT(sizeof(T) < sizeof(int));
return a < b ? a:b;
}
int main()
{
cout << my_min((short)1,(short)3);
//cout << my_min(1L,3L);
return 0;
}
一切源于对计算机的热爱

浙公网安备 33010602011771号