2013-05-19 22 views
0

我創建了一個C++ 11類,我想要解析一個字符串並根據字符串中的數據返回一個對象。我想返回的對象定義爲:從函數返回不同的模板專業化

// Container for the topic data and id 
template <typename T> 
class Topic 
{ 
public: 
    Topic(string id, T data) 
    : _id(id), _data(data) 
    {} 

private: 
    string _id; 
    T _data; 
}; 

返回對象的函數定義爲:

//解析字符串並將其拆分成組件

class TopicParser 
{ 
public: 
    template <class T> 
    static Topic<T> 
    parse(string message) 
    { 
    T data; // string, vector<string> or map<string, string> 
    string id = "123"; 
    Topic<T> t(id, data); 
    return t; 
    } 
}; 

我(認爲我)想能夠以這種方式調用函數:

string message = "some message to parse..."; 
auto a = TopicParser::parse<Topic<vector<string>>>(message); 
auto b = TopicParser::parse<Topic<string>>(message); 

但編譯器抱怨插件:

no matching function for call to ‘Topic<std::vector<std::basic_string<char> > >::Topic()’ 

如你所知,我不是模板專家。我正在嘗試使用模板的批准方式,我應該更喜歡其他方法嗎?

+0

你聲明'parse'方法爲靜態,我覺得編譯器會從你期望定義每個和你想在你的代碼的某個地方利用一切專業。 – didierc

+1

您正在將'Topic '作爲模板參數傳遞給'parse '。它返回'主題'。你想要「主題<主題>'回來嗎? –

回答

4

使用Topic<vector<string>>作爲模板參數在這裏沒用,我猜。只是刪除Topic

auto a = TopicParser::parse<vector<string>>(message); 
auto b = TopicParser::parse<string>(message); 
+0

是的,我誤解了我定義T來表示的東西。謝謝! –