實用工具類在中大型 C++ 項目中不可或缺,但標準 STL 僅提供少量基礎容器。Boost 通過多個高質量庫填補這一空白,本文介紹五個常用組件:tuple、static_assert、pool、random、program_options。所有代碼基於 Boost 1.35、GCC 3.4.4 測試。
C++ 函數只能返回單一值,早期常用結構體或 std::pair 變通。boost::tuple 支持最多 10 個異構元素,語法直觀。
#include <iostream>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_io.hpp>
#include <boost/tuple/tuple_comparison.hpp>
using namespace boost;
int main() {
tuple<int, char, float> t(2, 'a', 0.9);
std::cout << t << std::endl; // 輸出: (2 a 0.9)
return 0;
}
make_tuple 輔助創建,支持從函數返回。get<N>(t) 或 t.get<N>() 訪問元素,可修改非 const tuple 的元素。==, < 等)按字典序比較。斷言在編譯期生效,不生成任何運行時代碼,適合驗證模板參數、類型大小、靜態條件等。
#include <boost/static_assert.hpp>
int main() {
BOOST_STATIC_ASSERT(sizeof(int) == 4); // 64 位平台可能失敗
return 0;
}
失敗時編輯器報錯(如 incomplete type boost::STATIC_ASSERTION_FAILURE<false>),指明行號。
sizeof(MyStruct) == 16)boost::is_signed、is_convertible 等 traits)傳統 rand()/srand() 質量較差且非線程安全。Boost.Random 將引擎(生成器)與分布分離,靈活組合。
mt19937(梅森旋轉)、kreutzer1986 等uniform_int、uniform_real、normal_distribution、poisson_distribution 等variate_generator 綁定引擎與分布#include <boost/random.hpp>
using namespace boost;
int main() {
uniform_int<> dist(1, 100);
mt19937 eng;
variate_generator<mt19937, uniform_int<> > gen(eng, dist);
for (int i = 0; i < 100; ++i) std::cout << gen() << std::endl;
return 0;
}
頻繁分配/釋放小對象時,內存池能顯著提升性能並自動防止洩漏。僅需頭文件,無需鏈接庫。
pool:類 malloc 接口,按塊大小分配,不調用構造/析構。object_pool:對象感知接口,自動調用構造/析構,construct() 返回類型指針。singleton_pool:單例模式池,靜態方法調用,適合全局共享。pool_allocator / fast_pool_allocator:STL 容器分配器適配器。// pool 接口
pool<> p(10 * sizeof(A));
A* a = (A*)p.malloc(); // 不調用構造函數
p.purge_memory(); // 批量釋放
// object_pool 接口
object_pool<A> q;
A* a = q.construct(); // 調用構造函數
// 析構時自動調用 ~A()
結構化處理命令行參數,支持長/短選項、多值、位置參數、幫助信息自動生成。
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main(int ac, char* av[]) {
po::options_description desc("Options");
desc.add_options()
("help,h", "Show help")
("file", po::value<std::string>(), "Input file");
po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
if (vm.count("help")) std::cout << desc << std::endl;
if (vm.count("file")) std::cout << "File: " << vm["file"].as<std::string>() << std::endl;
return 0;
}
("help,h", ...)value<vector<string>>()positional_options_description 將無選項參數映射到選項