我正在尝试实现一个通用的配置文件解析器,我想知道如何在我的类中编写一个方法,该方法能够根据输入参数的类型来确定它的返回类型。我的意思是:
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:
发布于 2012-06-18 17:46:27
您所显示的代码中的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");在这里,您需要显式地使用模板参数,或者使用返回代理类而不是实际对象的技巧,并定义一个隐式转换操作符。乱七八糟的,而且大多数时候都是不必要的。
https://stackoverflow.com/questions/11080343
复制相似问题