C++ 傳統使用 void* 實現「萬能容器」,但缺乏型別安全。Boost 提供 boost::any:型別安全、支援任意型別、效率優於 variant。本文詳解用法、異常處理與實戰範例。
any_cast<T>() 進行執行期型別檢查boost::bad_any_cast 異常boost::any ai, as;
ai = 100; // 存入 int
as = std::string("hello"); // 存入 string
int i = boost::any_cast<int>(ai); // 取出 int
std::string s = boost::any_cast<std::string>(as); // 取出 string
// 型別不匹配會拋出異常
try {
int err = boost::any_cast<int>(as); // as 實為 string
} catch (boost::bad_any_cast& e) {
// 處理錯誤
}
void print(boost::any it) {
if (it.empty()) { printf("nothing!\n"); return; }
if (it.type() == typeid(int)) {
printf("integer: %d\n", boost::any_cast<int>(it));
} else if (it.type() == typeid(std::string)) {
printf("string: %s\n", boost::any_cast<std::string>(it).c_str());
} else if (it.type() == typeid(CString)) { // MFC 字串
_tprintf(_T("CString: %s\n"), boost::any_cast<CString>(it));
} else if (it.type() == typeid(Cat)) { // 自訂類別
_tprintf(_T("oops! a cat!\n"));
}
}
#include "stdafx.h"
#include "boost/any.hpp"
#include <string>
using namespace std;
using namespace boost;
class Cat {};
void print(any it) {
if (it.empty()) { printf("nothing!\r\n"); return; }
if (it.type() == typeid(int)) {
printf("integer: %d\r\n", any_cast<int>(it)); return;
}
if (it.type() == typeid(string)) {
printf("string: %s\r\n", any_cast<string>(it).c_str()); return;
}
if (it.type() == typeid(CString)) {
_tprintf(_T("CString: %s\r\n"), any_cast<CString>(it)); return;
}
if (it.type() == typeid(Cat)) {
_tprintf(_T("oops! a cat!\r\n")); return;
}
}
int main() {
print(100); // 直接傳遞字面值,隱式轉 any
any as[] = { any(), 100, string("hello"), CString("world"), Cat() };
for (int i = 0; i < sizeof(as)/sizeof(as[0]); ++i)
print(as[i]);
return 0;
}
integer: 100
nothing!
integer: 100
string: hello
CString: world
oops! a cat!

| 特性 | void* | boost::any |
|---|---|---|
| 型別安全 | 無(需自行管理) | 編譯期+執行期雙重保障 |
| 物件語意 | 僅記憶體位址 | 保存完整物件(含建構/解構) |
| 異質容器 | 手工實現 | 原生支援 vector<any> |
| 效能 | 極高(零開銷) | 略高於 void*(型別擦除開銷) |
建議:現代 C++ 專案中需異質容器時,優先選擇
boost::any(或 C++17std::any),除非極度敏感效能且型別固定可用variant。
本文出自 “白喬博客” 博客,請務必保留此出處 https://bluejoe.blog.51cto.com/807902/192762