根据输入参数确定返回类型

时间:2012-06-18 09:44:28

标签: c++ templates boost return-type

我正在尝试实现通用配置文件解析器,我想知道如何在我的类中编写一个能够根据输入参数的类型确定其返回类型的方法。这就是我的意思:

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 :(

1 个答案:

答案 0 :(得分:5)

您展示的代码中的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");

在这里,您需要使模板参数显式化,或者使用返回代理类而不是实际对象的技巧,并定义隐式转换运算符。凌乱,大部分时间都没必要。

相关问题