[英]Classify Types in Boost Variant using Visitor does not compile
[英]using boost visitor to convert between types
讓我們說我有一個
boost::variant<std::string, int> myVariant;
在這個對象中,我保存數據庫中的數據,通常是整數或文本,但有時候是作為文本存儲在數據庫中的時間。 所以我想知道我是否可以創建一個訪問者,當訪問帶有字符串的variant對象時,返回一個類型為'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時出現問題,甚至會返回。 有誰知道如何實現這一目標? 我能以某種方式定義帶有兩個參數的訪客...或者其他東西嗎?
您直接的示例調用應該有效。 向訪問者添加構造函數,該構造函數接受引用並存儲它,如:
tm* target;
timeVisitor( tm& a ) : target(&a) {}
int operator()(string &str) const {
strptime(str.c_str(), "%Y-%m-%d", target);
}
實際上,完全允許在創作時給參觀者一個參數。 您在問題結束時編寫的代碼是執行此操作的好方法:
tm result;
int returnCode = boost::apply_visitor( timeVisitor(result), myVariant );
以下是訪問者的樣子:(未經過我的測試,可能會出現輕微的語法錯誤)
class timeVisitor : public boost::static_visitor<bool>
{
public:
timeVisitor(tm& s):m_tm(s) {}
bool operator()(string &str) const
{
return strptime(str.c_str(), "%Y-%m-%d", m_tm.get());
// in case of error, NULL pointer is converted to false automatically
}
protected:
tm& m_tm;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.