一、禁止一个类拷贝构造和拷贝赋值
#include <boost/noncopyable.hpp>
using namespace boost;
//继承boost::noncopyable即可禁用拷贝构造和拷贝赋值
class do_not_copy : public boost::noncopyable
{};
int main()
{
do_not_copy d1;
// do_not_copy d2(d1); //报错
// do_not_copy d3;
// d3 = d1; //报错
}
二、让编译器对一个未使用的变量不报警告
#include <boost/core/ignore_unused.hpp>
int func(int x, int y)
{
int i;
ignore_unused(x, i);
return y;
}
三、函数返回未初始化的无效值
#include <boost/optional.hpp>
using namespace boost;
optional<int> getValue(int x)
{
if(x > 6)
return optional<int>(x*x);
else
return optional<int>(boost::none);
}
int main()
{
optional<int> a = getValue(33);
if(a.is_initialized())
qDebug()<<"a = "<<a.value();
else
qDebug()<<"返回值是未初始化的无效值";
a = getValue(4);
if(a.is_initialized())
qDebug()<<"a = "<<a.value();
else
qDebug()<<"返回值是未初始化的无效值";
}
条件构造:
#include <boost/optional.hpp>
using namespace boost;
optional<int> getValue(int x)
{
return optional<int>(x > 6,x*x);
}
int main()
{
optional<int> a = getValue(33);
if(a)
qDebug()<<"a = "<<a.value();
else
qDebug()<<"返回值是未初始化的无效值";
a = getValue(4);
if(a)
qDebug()<<"a = "<<a.value();
else
qDebug()<<"返回值是未初始化的无效值";
}
结果同上。
#include <boost/optional.hpp>
using namespace boost;
class test
{
public:
test(int value = 0):value(value)
{}
void show()
{
qDebug()<<value;
}
private:
int value;
};
optional<test> getValue(int x)
{
return optional<test>(x > 6,test(x));
}
int main()
{
optional<test> a = getValue(33);
if(a)
a.value().show();
else
qDebug()<<"返回值是未初始化的无效值";
a = getValue(4);
if(a)
a.value().show();
else
qDebug()<<"返回值是未初始化的无效值";
}
四、一些容器的重载操作(对Qt不算太实用)
#include <boost/assign.hpp>
using namespace boost;
using namespace boost::assign;
int main()
{
QList<int> list;
push_back(list)(1)(2)(3)(4)(5);
qDebug()<<list;
push_front(list)(111)(2222)(3333)(444)(555);
qDebug()<<list;
}
五、三态bool
#include <boost/logic/tribool.hpp>
#include <boost/logic/tribool_io.hpp>
using namespace boost;
int main()
{
tribool tb1 = false;
tribool tb2 = true;
tribool tb3 = indeterminate;//不确定态
if(true){}
if(false){}
if(indeterminate(tb3)){}
// std::cout<<tb1<<" "<<tb2<<" "<<tb3<<std::endl;//0 1 2
}
六、当前函数名称
#include <boost/current_function.hpp>
double func(QString str)
{
std::cout << __FUNCTION__ << std::endl;
std::cout << BOOST_CURRENT_FUNCTION << std::endl;
return 0.0;
}
int main()
{
std::cout << __FUNCTION__ << std::endl;
std::cout << BOOST_CURRENT_FUNCTION << std::endl;
func(QString());
}