我想實現一個通用的配置文件解析器,我想知道如何在我的類中編寫一個方法,該方法能夠根據輸入的類型確定其返回類型參數。這裏就是我的意思是:基於輸入參數確定返回類型
class Config
{
...
template <typename T>
T GetData (const std::string &key, const T &defaultValue) const;
...
}
爲了調用上面的方法,我不得不使用這樣的事情:
some_type data = Config::GetData<some_type>("some_key", defaultValue);
我怎樣才能擺脫多餘的規範?我看到的boost :: property_tree :: ptree中:: get()方法是能夠做到這招,但實現比較複雜,我無法破譯這個複雜的聲明:
template<class Type, class Translator>
typename boost::enable_if<detail::is_translator<Translator>, Type>::type
get(const path_type &path, Translator tr) const;
如果可能的話,我想這樣做,而不會在使用我的Config類的代碼中創建依賴boost。
PS:我是一個的n00b當談到C++模板:(
模板類是一個選項嗎?例如,你可以編寫'template class Config {}'並使用'Config instance'實例化';之後,使用'instance'來處理,你不需要指定東西。 –
魯道夫的回答如下,我正在尋找。不管怎麼說,還是要謝謝你。 –