はじめに
BoostはC++の事実上の標準拡張ライブラリ。多くの機能が後に標準に取り込まれている。
「標準にないけど便利なやつ」が見つかる宝箱だよ。
インストール
# Ubuntu/Debian
sudo apt install libboost-all-dev
# macOS
brew install boost
# Windows (vcpkg)
vcpkg install boost:x64-windows
よく使うBoostライブラリ
1. Boost.Optional(→ std::optional)
#include <boost/optional.hpp>
boost::optional<int> find_value(int key) {
if (key > 0) return key * 2;
return boost::none;
}
auto result = find_value(5);
if (result) {
std::cout << "Found: " << *result << std::endl;
}
// デフォルト値
int value = result.value_or(-1);
2. Boost.Filesystem(→ std::filesystem)
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
// パス操作
fs::path p("/usr/local/bin/app");
std::cout << "stem: " << p.stem() << std::endl;
std::cout << "extension: " << p.extension() << std::endl;
std::cout << "parent: " << p.parent_path() << std::endl;
// ディレクトリ操作
fs::create_directories("a/b/c");
for (auto& entry : fs::directory_iterator(".")) {
std::cout << entry.path() << std::endl;
}
// ファイル操作
if (fs::exists("file.txt")) {
auto size = fs::file_size("file.txt");
}
3. Boost.Variant(→ std::variant)
#include <boost/variant.hpp>
using Var = boost::variant<int, double, std::string>;
Var v = 42;
std::cout << boost::get<int>(v) << std::endl;
v = "hello";
std::cout << boost::get<std::string>(v) << std::endl;
// ビジター
struct Visitor : boost::static_visitor<void> {
void operator()(int i) const { std::cout << "int: " << i << std::endl; }
void operator()(double d) const { std::cout << "double: " << d << std::endl; }
void operator()(const std::string& s) const { std::cout << "string: " << s << std::endl; }
};
boost::apply_visitor(Visitor(), v);
4. Boost.Lexical_cast
#include <boost/lexical_cast.hpp>
// 文字列→数値
int i = boost::lexical_cast<int>("123");
double d = boost::lexical_cast<double>("3.14");
// 数値→文字列
std::string s = boost::lexical_cast<std::string>(42);
// エラーハンドリング
try {
int x = boost::lexical_cast<int>("not a number");
} catch (const boost::bad_lexical_cast& e) {
std::cerr << "Conversion failed: " << e.what() << std::endl;
}
5. Boost.Format
#include <boost/format.hpp>
// printf風フォーマット
std::cout << boost::format("Hello, %s! You are %d years old.") % "Alice" % 25;
// 位置指定
std::cout << boost::format("%2% %1%") % "world" % "Hello";
// 書式指定
std::cout << boost::format("%08d") % 42; // 00000042
std::cout << boost::format("%.2f") % 3.14159; // 3.14
6. Boost.Regex
#include <boost/regex.hpp>
std::string text = "Email: user@example.com";
boost::regex pattern(R"(\w+@\w+\.\w+)");
// マッチ検索
boost::smatch match;
if (boost::regex_search(text, match, pattern)) {
std::cout << "Found: " << match[0] << std::endl;
}
// 置換
std::string result = boost::regex_replace(text, pattern, "[EMAIL]");
7. Boost.Algorithm/String
#include <boost/algorithm/string.hpp>
std::string s = " Hello, World! ";
// トリム
boost::trim(s);
// 大文字・小文字変換
boost::to_upper(s);
boost::to_lower(s);
// 分割
std::vector<std::string> parts;
boost::split(parts, "a,b,c", boost::is_any_of(","));
// 結合
std::string joined = boost::algorithm::join(parts, "-");
// 置換
boost::replace_all(s, "World", "Boost");
8. Boost.Any(→ std::any)
#include <boost/any.hpp>
boost::any a = 42;
std::cout << boost::any_cast<int>(a) << std::endl;
a = std::string("hello");
std::cout << boost::any_cast<std::string>(a) << std::endl;
// 型チェック
if (a.type() == typeid(std::string)) {
std::cout << "It's a string!" << std::endl;
}
9. Boost.Smart_ptr(→ std::shared_ptr等)
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
auto p = boost::make_shared<int>(42);
std::cout << *p << std::endl;
std::cout << "use_count: " << p.use_count() << std::endl;
boost::weak_ptr<int> wp = p;
if (auto sp = wp.lock()) {
std::cout << "Still alive: " << *sp << std::endl;
}
10. Boost.Program_options
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main(int argc, char* argv[]) {
po::options_description desc("Options");
desc.add_options()
("help,h", "Help message")
("input,i", po::value<std::string>(), "Input file")
("verbose,v", "Verbose output")
("count,c", po::value<int>()->default_value(1), "Count");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return 0;
}
if (vm.count("input")) {
std::cout << "Input: " << vm["input"].as<std::string>() << std::endl;
}
}
Boostと標準ライブラリの対応
| Boost | C++標準 |
|---|---|
| Boost.Optional | std::optional (C++17) |
| Boost.Variant | std::variant (C++17) |
| Boost.Any | std::any (C++17) |
| Boost.Filesystem | std::filesystem (C++17) |
| Boost.Regex | std::regex (C++11) |
| Boost.Smart_ptr | std::shared_ptr (C++11) |
| Boost.Thread | std::thread (C++11) |
| Boost.Chrono | std::chrono (C++11) |
CMakeでの使用
find_package(Boost 1.70 REQUIRED COMPONENTS filesystem system)
target_link_libraries(myapp PRIVATE Boost::filesystem Boost::system)
まとめ
Boostは「C++の未来を先取り」するライブラリ集です。C++17以降で標準化された機能も多いですが、まだBoostにしかない便利機能もたくさんあります!