首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

白喬原創:萬能類型 boost::any 詳解與實戰

     編輯:關於C語言

前言

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!

boost::any 執行結果

六、 與 void* 對比總結

特性void*boost::any
型別安全無(需自行管理)編譯期+執行期雙重保障
物件語意僅記憶體位址保存完整物件(含建構/解構)
異質容器手工實現原生支援 vector<any>
效能極高(零開銷)略高於 void*(型別擦除開銷)

建議:現代 C++ 專案中需異質容器時,優先選擇 boost::any(或 C++17 std::any),除非極度敏感效能且型別固定可用 variant。


本文出自 “白喬博客” 博客,請務必保留此出處 https://bluejoe.blog.51cto.com/807902/192762

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved