萬能資料型別any雜談

2021-06-15 18:30:27 字數 2178 閱讀 7419

萬能資料型別boost::any雜談

1、boost::any 與 _variant_t

剛接觸boost::any時,不禁讓人想起了ms的_variant_t類,因為兩者都可以存放其他的型別的值。

比較一下兩者可以發現:_variant_t只能容納 variant 資料型別(詳見msdn),而boost::any可以容納用

戶自定義資料型別,如結構體,類等,這由兩者的實現方法不同造成的:

_variant_t利用的是過載機制,即_variant_t中過載了若干個拷貝建構函式和賦值函式(看起來有點恐怖)

,從而實現了ariant 資料型別能夠向_variant_t型別轉換。正是如此限制了其與其它資料型別間的轉換。

boost::any則充分利用了模板機制,只需乙個模板拷貝建構函式和模板賦值函式就實現了各種資料型別向

boost::any的轉換,省去了過載之苦,甚是妙哉!

2、boost::any 與 cbcgpprop

boost::any的幫助文件中提到它的乙個應用,可以用來構建屬性,如下:

struct property

;typedef std::listproperties;

這令我想起在bcg中有乙個屬性類cbcgpprop。cbcgpprop提供了有關屬性的管理(詳見bcgp源**),其內部使

用的是_variant_t接收各中 variant 資料型別。

根據struct property,我寫了乙個小小的測試程式,詳見附錄。

3、boost::any之使用

boost::any的結構十分簡單,只有幾個成員函式。

1)給boost::any賦值

某個資料型別要賦值給boost::any,需要滿足三個條件:

*a valuetype is copyconstructible .

*a valuetype is optionally assignable.

*the destructor for a valuetype upholds the no-throw exception-safety guarantee.

eg:int i = 100;

boost::any anyint= i;

boost::any anydouble(200.0);

注:把字串賦給boost::any時需要借助std::string

boost::any anystr;

//anystr = "haha";    //wrong! "haha"會被看成是char

anystr = std::string("haha"); //right

2)把boost::any的值賦給某個變數

這需要借助boost::any_cast模板函式。當轉換失敗是會丟擲bad_any_cast異常。

//bad_any_cast

boost::any anydouble(200.5);

float fvalue = 0.0;

trycatch(boost::bad_any_cast& e);

property(const std::string & name,

const boost::any & value)

;std::string m_name;

boost::any m_value;

};typedef std::listproperties;

void outputproperty(properties props)

person.clear();

//把自定義型別賦值給boost::any

boost::any anyclass;

property prop;

anyclass = prop;

const std::type_info& info = anyclass.type();

std::cout << info.name();

//字串

boost::any anystr;

//anystr = "haha";  //wrong

anystr = std::string("haha");

const std::type_info& infostr = anystr.type();

std::cout << infostr.name();

return 0;

}

萬能型別boost any

本節簡單介紹boost庫中與數值相關的boost any boost lexical cast,以及有理數類boost rational。boost庫提供了any類,boost any是乙個能儲存任意型別值的類,這一點有點像variant型別,不過variant由於採用了乙個巨大的union,效率非...

白喬原創 萬能型別boost any

4.6 使用第三方庫 以上介紹了visual c 對物件賦值 轉換及字元編碼轉換的方法,實際上還有一些好用的第三方類庫用以輔助c 程式設計師完成物件處理,比較著名的就是boost。本節簡單介紹boost庫中與數值相關的boost any boost lexical cast,以及有理數類boost ...

白喬原創 萬能型別boost any

4.6 使用第三方庫 以上介紹了visual c 對物件賦值 轉換及字元編碼轉換的方法,實際上還有一些好用的第三方類庫用以輔助c 程式設計師完成物件處理,比較著名的就是boost。本節簡單介紹boost庫中與數值相關的boost any boost lexical cast,以及有理數類boost ...