2011-10-27 69 views
0
之間的轉換

比方說,我有一個提升訪客類型

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問題甚至會回來。 有誰知道這可以實現?我能以某種方式定義帶有兩個參數的訪客...或者其他的東西嗎?

回答

1

您的直接示例調用應該可以工作。構造再加上需要一個參考和存儲它,像訪問者:

tm* target; 
timeVisitor(tm& a) : target(&a) {} 
int operator()(string &str) const { 
     strptime(str.c_str(), "%Y-%m-%d", target); 
} 
+0

是的!那一個工作完美...我知道我需要一點點推動,但是這些提升庫有時候有點混亂。我不知道的是,既然我有boost :: variant ,那麼我還必須定義以int(int)作爲參數的operator()!並從錯誤消息中找到不是很容易:(。 – pinpinokio

1

事實上,這是完全允許讓遊客在創建一個參數。你在你的問題的最後寫的代碼是做到這一點的好辦法:

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; 
}; 
+0

爲什麼在已經傳入結果時構建'shared_ptr'? – Xeo

+0

@Xeo:實際上,我太匆忙了。更新。謝謝。 – Offirmo