Boost 第四章 实用工具

本文章所有内容源于《BOOST程序库完全开发指南:深入C++“准”标准库(第3版)》第四章


1. noncopyable

1.1 功能:

实现一个禁止拷贝的类

1.2 头文件:

#include <boost/noncopyable.hpp>
或者
#include <boost/utility,hpp>

1.3 用法:

#include <boost/noncopyable.hpp>
//继承noncopyable,noncopyable中是禁止copy的,这里缺省了私有继承private,但是也可以允许
class do_not_copy : boost :: noncopyable       
{...};

2.ignore_unused

2.1 功能:

关闭GCC编译器发出的无用的警告

2.2 头文件:

#include <boost/core/ignore_unused.hpp>
using namespace boost;

2.3 用法:

基本用法

#include <boost/core/ignore_unused.hpp>
using namespace boost;
int main(int x, int y)
{
	/*---------------------问题版-----------------------------*/
	int i ;				//会警告未使用变量x和i
	return y;
	/*---------------------解决版-------------------------------*/
	int i;
	ignore_unused(x,i);     //相当于(void)x;(void)i;
	return y;
}

模板用法

#include <boost/core/ignore_unused.hpp>
using namespace boost;
int main()
{
	typedef int result_type;			//暂未使用的类型定义
	ignore_unused<result_type>();   //忽略未使用的类型定义
}

3.optional

3.1 功能:

使用“容器”语义,包装了“可能产生无效值”的对象,实现了“未初始化”的概念,为这种“无效值”提供了一个更好的解决方案。

3.2 头文件:

#include <boost/optional.hpp>
using namespace boost;

3.3 用法:

首先可以把它认为是一个大小为1,并且行为类似指针的容器。
基本用法

#include <boost/optional.hpp>
using namespace boost;
int main()
{
    optional<int> op0;								  	//一个未初始化的optional对象
    optional<int> op1(none);					//使用none赋予未初始化值

    assert(!op0);
    assert(op0 == op1);								//比较两个optional对象
    assert(op1.value_or(253) == 253);	//获取缺省值

    cout << op1.value_or_eval(				//使用函数对象,lambda表达式定义函数对象
            [](){return 874;}) << endl;

    optional<string> ops("test");				//初始化字符串test
    cout << *ops << endl;

    ops.emplace("monado", 3);
    assert(*ops == "mon");

    vector<int> v(10);
    optional<vector<int>& > opv(v);		//容纳一个容器的引用
    assert(opv);												//bool转型

    opv->push_back(5);
    assert(opv->size() == 11);

    opv = none;												//置为初始化
    assert(!opv);												//此时为无效值
}

复杂例子

#include <boost/optional.hpp>
using namespace boost;
optional<double> calc(int x)										//计算倒数
{
    return optional<double>( x != 0, 1.0 / x);			//条件构造函数
}

optional<double> sqrt_op(double x)						//计算实数的平方根
{
    return optional<double>(x > 0, sqrt(x));			//条件构造函数
}

int main()
{
    optional<double> d = calc(10);

    if (d)																					//bool语境测试optional的有效性
    {
        cout << *d << endl;
        cout << d.value() << endl;
    }

    d = sqrt_op(-10);
    if (!d)
    {   cout << "no result"<< endl; }
}

4. assign

4.1 功能:

为容器初始化或者赋值,填入大量的数据,有了该库就可以不再反复调用insert()和push_back()。

4.2 头文件:

#include <boost/assign.hpp>
using namespace boost;

4.3 用法:

三个工厂函数list_of()、map_list_of()/pair_list_of()、tuple_list_of()

5. swap

5.1 功能:

为交换两个变量的值提供了边界的方法

5.2 头文件:

#include <boost/swap.hpp>

5.3 用法:

#include <boost/swap.hpp>
int main()
{
	int a1[10];
	int a2[10];
	std::fill_n(a1,10,5);
	std::fill_n(a2,10,20);
	
	boost::swap(a1,a2);
}

6. singleton

6.1 功能:

单件模式,该模式的类在生命周期里有且仅有一个实例。

6.2 头文件:

#include <boost/serialization/singleton.hpp>
using boost::serialization::singleton;

6.3 用法:

7. tribool

7.1 功能:

基于三态的布尔逻辑:true、false、indeterminate(未知)

7.2 头文件:

#include <boost/logic/tribool.hpp>
using namespace boost;

7.3 用法:

#include <iostream>
using namespace std;
#include <boost/logic/tribool.hpp>
#include <boost/logic/tribool_io.hpp>
using namespace boost;

//
void case1()
{
    tribool tb(true);														//值为true的tribool
    tribool tb2(!tb);														//值为false

    if (tb)																				//tb==true
    {   cout << "true" << endl; }

    tb2 = indeterminate;											//tb2为不确定
    assert(indeterminate(tb2));							//用indeterminate函数检测状态
    cout << "tb2 = " << tb2 << endl;

    if (tb2 == indeterminate)
    {   cout << "indeterminate" << endl;    }

    if (indeterminate(tb2))
    {   cout << "indeterminate" << endl;    }

    cout << (tb2 || true )<< endl;								//输出true
    cout << (tb2 && false )<< endl;							//输出flase

}

//
void case2()
{
    tribool tb(indeterminate);

    if (tb)
        cout << "never reach here" << endl;
    if (!tb)
        cout << "never reach here" << endl;

    if (indeterminate(tb))
        cout << "indeterminate" << endl;
}

//
BOOST_TRIBOOL_THIRD_STATE(unknown)

namespace tmp_ns
{
        BOOST_TRIBOOL_THIRD_STATE(unknown)
};


void case3()
{
    tribool tb(tmp_ns::unknown);
    assert(unknown(tb));
    assert(unknown(tb || false));

}

//
#include <boost/optional.hpp>
using namespace boost;

void case4()
{
    optional<bool> b;

    if (!b)
    {   cout << "indeterminate" << endl;    }				//未初始化,既不是true也不是false

    b = false;
    if (b)
    {   cout << "b=" << *b << endl; }									//b有值为false

    if (!b)
    {   cout << "false" << endl;    }

    if (b && !*b)
    {   cout << "real false" << endl;    }

}

//

int main()
{
    case1();
    case2();
    case3();
    case4();
}

8. operators

8.1 功能:

重载

8.2 头文件:

8.3 用法:

9. exception

9.1 功能:

改变传统的似乎用错误返回值的处理模式,看着更好。

9.2 头文件:

#include <boost/exception/all.hpp>
using namespace boost;

9.3 用法:

10. uuid

10.1 功能:

生成一段标识符。

10.2 头文件:

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
using namespace boost::uuids;

10.3 用法:

// Copyright (c) 2015
// Author: Chrono Law
using namespace std;
#include <iostream>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
using namespace boost::uuids;

//
void case1()
{
    uuid u ;
    assert(uuid::static_size() == 16);
    assert(u.size() == 16);

    vector<unsigned char> v(16, 7);
    std::copy(v.begin(), v.end(), u.begin());
    assert(u.data[0] == u.data[1]
            && u.data[15] == 7);

    cout << u << endl;
    std::fill_n(u.data+ 10,6, 8);

    cout << u << endl;
    cout << "-------------------------"<<endl;
}

//
void case2()
{
    uuid u ;

    std::fill_n(u.begin(), u.size(), 0xab);
    assert(!u.is_nil());
    assert(u.variant() == u.variant_rfc_4122);
    assert(u.version() == u.version_unknown);
    cout << u << endl;

    std::memset(u.data, 0, 16);
    assert(u.is_nil());
    uuid u1 ,u2;

    std::fill_n(u1.begin(), u1.size(), 0xab);
    std::fill_n(u2.begin(), u2.size(), 0x10);
    assert(u1 != u2 && u1 > u2);

    u2.data[0] = 0xff;
    assert( u1 < u2);

    std::memset(u1.data, 0, 16);
    std::memset(u2.data, 0, 16);
    assert(u1 == u2);
    cout << "-------------------------"<<endl;
}

//
void case3()
{
    uuid u = nil_generator()();
    assert(u.is_nil());

    u = nil_uuid();
    assert(u.is_nil());

    string_generator sgen;

    uuid u1 = sgen("0123456789abcdef0123456789abcdef");
    cout << u1 << endl;
    uuid u2 = sgen("01234567-89ab-cdef-0123-456789abcdef");
    cout << u2 << endl;
    uuid u3 = sgen(L"{01234567-89ab-cdef-0123-456789abcdef}");
    cout << u3 << endl;
    cout << "-------------------------"<<endl;
}

//
void case4()
{
    uuid www_xxx_com= string_generator()
        ("{0123456789abcdef0123456789abcdef}");
    name_generator ngen(www_xxx_com);

    uuid u1 = ngen("mario");
    assert(!u1.is_nil() &&
            u1.version() == uuid::version_name_based_sha1);

    uuid u2 = ngen("link");
    cout << u2 << endl;

    random_generator rgen;

    uuid u = rgen();
    assert(u.version()== uuid::version_random_number_based);
    cout << u << endl;
    cout << "-------------------------"<<endl;
}

//
class uuid_t : public uuid
{
private:
    static random_generator& rand_uuid()
    {
        static random_generator gen;
        return gen;
    }
    static string_generator& string_uuid()
    {
        static string_generator gen;
        return gen;
    }

public:
    uuid_t(): uuid(rand_uuid()()){}
    uuid_t(int): uuid(nil_uuid()){}
    uuid_t(const char* str): uuid(string_uuid()(str)) {}
    uuid_t(const uuid& u, const char* str):
        uuid(name_generator(u)(str))    {}
    explicit uuid_t(const uuid& u): uuid(u){}

    operator uuid()
    {   return static_cast<uuid&>(*this);   }
    operator uuid() const
    {   return static_cast< const uuid&>(*this);}
};

void case5()
{
    uuid_t u0 = 0;
    assert(u0.is_nil());

    uuid_t u1,u2;
    cout << u1 << endl;
    cout << u2 << endl;

    uuid_t u3("{01234567-89ab-cdef-0123-456789abcdef}");
    cout << u3 << endl;

    cout << uuid_t(u3, "test name gen") << endl;
    cout << "-------------------------"<<endl;
}

//
#include <boost/lexical_cast.hpp>
using namespace boost;

void case6()
{
    uuid u = string_generator()
        ("01234567-89ab-cdef-0123-456789abcdef");

    string str = to_string(u);
    cout << str << endl;

    {
        uuid u = lexical_cast<uuid>
            ("01234567-89ab-cdef-0123-456789abcdef");
        cout << u << endl;
        string str = lexical_cast<string>(u);
        cout << str << endl;

    }
    cout << "-------------------------"<<endl;
}
/*
//
#include <boost/version.hpp>
#if BOOST_VERSION <= 106400
#include <boost/uuid/sha1.hpp>
#else
#include <boost/uuid/detail/sha1.hpp>
#endif
using namespace boost::uuids::detail;

void case7()
{
    sha1 sha;

    const char *szMsg = "a short message";
    sha.process_byte(0x10);
    sha.process_bytes(szMsg, strlen(szMsg));
    sha.process_block(szMsg, szMsg + strlen(szMsg));

    unsigned int digest[5];
    sha.get_digest(digest);
    for (int i = 0; i < 5 ; ++i)
    {
        cout << hex << digest[i];
    }
}

*/
//

int main()
{
    case1();
    case2();
    case3();
    case4();
    case5();
    case6();
    // case7();
}

11. config

11.1 功能:

将程序的编译配置分解为三个正交部分:平台、编译器和标准库,解决特定平台编译器的兼容问题。

11.2 头文件:

#include <boost/config/suffix.hpp>

11.3 用法:

12. utility

12.1 功能:

包括很多小库

12.2 头文件:

#include <boost/utility/binary.hpp>
#include <boost/utility.hpp>
BOOST_BINARY

#include <boost/current_function.hpp>
BOOST_CURRENT_FUNCTION

12.3 用法:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值