Posted on 2008-06-10 17:27
RichardHe 閱讀(153)
評論(0) 編輯 收藏 引用
boost any庫(轉)
1. 可容納許多可能值類型的類型,比如int和string,并且可在它們之間自由
轉換,例如:將5作為"5"或者反之。這樣的類型在腳本語言和其他的解釋型語言中
較常見。boost::lexical_cast支持這種轉換功能。
2. 含有不同類型的值但并不試圖在它們之間進行轉換的可區分類型,即5嚴格
地作為一個int存放,不能隱式轉換為"5"或者5.0。它們不關心解釋,而關心有效
的類型安全性,是單一值的范型容器,不會產生有歧義的轉換。
3. 不可區分的類型,可以引用任何實際的類型,由程序員來保證所有形式的
訪問和解釋。C++中的void*提供了這樣的功能,同時它也會導致不確定的行為。
any類(基于Kevlin Henney在"Valued Conversions"中所述的同名類)是一個
基于第二類的可變值類型。它支持任意值類型的復制和有安全檢查的提取。一個提
供更多合適的運算符的類似設計,可用作一個一般的函數適配器any_function,一
個一般的迭代器適配器any_iterator等等。
例子
下面的代碼說明使用隱式轉換/復制到any對象的語法:
#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());
}
下面的判斷謂詞接著前面的定義,說明了any對象上查詢方法的使用:
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;
}
下面的類型源自OMG的屬性服務,為任意值類型定義了名字-值對:
struct property
{
property();
property(const std::string &, const boost::any &);
std::string name;
boost::any value;
};
typedef std::list<property> properties;
下面的基類說明了基于回調的運行時多態性的實現方法,其中的回調函數擁有任意
類型的參數。由于C++中缺少虛函數模板,不同的實現方法需要在效率,安全性和
通用性之間作權衡。使用一個帶類型檢查的可變類型提供了一種解決途徑:
class consumer
{
public:
virtual void notify(const any &) = 0;
...
};