比方說,我有一個提升訪客類型
boost::variant<std::string, int> myVariant;
在這個對象我一直從數據庫中,這通常是整數或文字,但有時數據是存儲在數據庫中的時間文本。 所以我想知道是否可以創建一個訪問者,當訪問帶有字符串的變體對象時,返回一個類型爲「tm」的結構體。類似的東西:
class timeVisitor : public boost::static_visitor<boost::shared_ptr<tm> >
{
public:
boost::shared_ptr<tm> operator()(string &str) const
{
boost::shared_ptr<tm> dst(new tm());
strptime(str.c_str(), "%Y-%m-%d", dst.get());
return dst;
}
};
然後才能使用它:
boost::shared_ptr<tm> result = boost::apply_visitor(timeVisitor(), myVariant);
的事情是,我不希望創建tm結構到訪客,更動一些共享指針和東西。我更願意將已創建的一個給予訪問者並在其內部進行初始化。 喜歡的東西(在使用的意義上):
tm result;
int returnCode = boost::apply_visitor(timeVisitor(result), myVariant);
的遊客將只是strptime我的結果tm結構的初始化,如果有與轉換成RETURNCODE問題甚至會回來。 有誰知道這可以實現?我能以某種方式定義帶有兩個參數的訪客...或者其他的東西嗎?
是的!那一個工作完美...我知道我需要一點點推動,但是這些提升庫有時候有點混亂。我不知道的是,既然我有boost :: variant,那麼我還必須定義以int(int)作爲參數的operator()!並從錯誤消息中找到不是很容易:(。 –
pinpinokio