【发布时间】:2012-06-18 09:44:28
【问题描述】:
我正在尝试实现一个通用配置文件解析器,我想知道如何在我的类中编写一个能够根据输入参数的类型确定其返回类型的方法。这就是我的意思:
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:在 C++ 模板方面,我是一个 n00b :(
【问题讨论】:
-
可以选择模板类吗?例如,您可以编写
template <typename T> class Config {}并使用Config<some_type> instance;对其进行实例化,然后使用instance进行处理,您无需指定任何内容。 -
鲁道夫的回答正是我想要的。还是谢谢。
标签: c++ templates boost return-type