2012-06-18 41 views
2

我想實現一個通用的配置文件解析器,我想知道如何在我的類中編寫一個方法,該方法能夠根據輸入的類型確定其返回類型參數。這裏就是我的意思是:基於輸入參數確定返回類型

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++模板:(

+0

模板類是一個選項嗎?例如,你可以編寫'template class Config {}'並使用'Config instance'實例化';之後,使用'instance'來處理,你不需要指定東西。 –

+0

魯道夫的回答如下,我正在尋找。不管怎麼說,還是要謝謝你。 –

回答

4

在代碼中的enable_if你已經證明做一些事情無關你的情況,你可以刪除顯式模板規範中,編譯器會推斷出它的參數:

some_type data = Config::GetData("some_key", defaultValue); 

更妙的是,在C++ 11,你甚至不需要指定變量類型的聲明,可以推斷,以及:

auto data = Config::GetData("some_key", defaultValue); 

......但請注意,C++只能從參數推斷模板參數,而不是返回類型。也就是說,下面就工作:

class Config { 
    … 
    template <typename T> 
    static T GetData(const std::string &key) const; 
    … 
} 
some_type data = Config::GetData("some_key"); 

在這裏,你要麼需要做的模板參數明確,或使用返回一個代理類,而不是實際的一招對象,並定義一個隱式轉換運算符。雜亂,大部分時間都是不必要的。

+0

Oooooh ...很整潔!我沒有嘗試過:D感謝一百萬! –