Posted on 2008-06-10 17:27
RichardHe 閱讀(153)
評(píng)論(0) 編輯 收藏 引用
boost any庫(kù)(轉(zhuǎn))
1. 可容納許多可能值類型的類型,比如int和string,并且可在它們之間自由
轉(zhuǎn)換,例如:將5作為"5"或者反之。這樣的類型在腳本語(yǔ)言和其他的解釋型語(yǔ)言中
較常見(jiàn)。boost::lexical_cast支持這種轉(zhuǎn)換功能。
2. 含有不同類型的值但并不試圖在它們之間進(jìn)行轉(zhuǎn)換的可區(qū)分類型,即5嚴(yán)格
地作為一個(gè)int存放,不能隱式轉(zhuǎn)換為"5"或者5.0。它們不關(guān)心解釋,而關(guān)心有效
的類型安全性,是單一值的范型容器,不會(huì)產(chǎn)生有歧義的轉(zhuǎn)換。
3. 不可區(qū)分的類型,可以引用任何實(shí)際的類型,由程序員來(lái)保證所有形式的
訪問(wèn)和解釋。C++中的void*提供了這樣的功能,同時(shí)它也會(huì)導(dǎo)致不確定的行為。
any類(基于Kevlin Henney在"Valued Conversions"中所述的同名類)是一個(gè)
基于第二類的可變值類型。它支持任意值類型的復(fù)制和有安全檢查的提取。一個(gè)提
供更多合適的運(yùn)算符的類似設(shè)計(jì),可用作一個(gè)一般的函數(shù)適配器any_function,一
個(gè)一般的迭代器適配器any_iterator等等。
例子
下面的代碼說(shuō)明使用隱式轉(zhuǎn)換/復(fù)制到any對(duì)象的語(yǔ)法:
#include <list>
#include <boost/any.hpp>
typedef std::list<boost::any> many;
void append_int(many & values, int value)
{
boost::any to_append = value;
values.push_back(to_append);
}
void append_string(many & values, const std::string & value)
{
values.push_back(value);
}
void append_char_ptr(many & values, const char * value)
{
values.push_back(value);
}
void append_any(many & values, const boost::any & value)
{
values.push_back(value);
}
void append_nothing(many & values)
{
values.push_back(boost::any());
}
下面的判斷謂詞接著前面的定義,說(shuō)明了any對(duì)象上查詢方法的使用:
bool is_empty(const boost::any & operand)
{
return operand.empty();
}
bool is_int(const boost::any & operand)
{
return operand.type() == typeid(int);
}
bool is_char_ptr(const boost::any & operand)
{
try
{
any_cast<const char *>(operand);
return true;
}
catch(const boost::bad_any_cast &)
{
return false;
}
}
bool is_string(const boost::any & operand)
{
return any_cast<std::string>(&operand);
}
void count_all(many & values, std::ostream & out)
{
out << "#empty == "
<< std::count_if(values.begin(), values.end(), is_empty) <<
std::endl;
out << "#int == "
<< std::count_if(values.begin(), values.end(), is_int) << std::
endl;
out << "#const char * == "
<< std::count_if(values.begin(), values.end(), is_char_ptr) <<
std::endl;
out << "#string == "
<< std::count_if(values.begin(), values.end(), is_string) <<
std::endl;
}
下面的類型源自O(shè)MG的屬性服務(wù),為任意值類型定義了名字-值對(duì):
struct property
{
property();
property(const std::string &, const boost::any &);
std::string name;
boost::any value;
};
typedef std::list<property> properties;
下面的基類說(shuō)明了基于回調(diào)的運(yùn)行時(shí)多態(tài)性的實(shí)現(xiàn)方法,其中的回調(diào)函數(shù)擁有任意
類型的參數(shù)。由于C++中缺少虛函數(shù)模板,不同的實(shí)現(xiàn)方法需要在效率,安全性和
通用性之間作權(quán)衡。使用一個(gè)帶類型檢查的可變類型提供了一種解決途徑:
class consumer
{
public:
virtual void notify(const any &) = 0;
...
};