【问题标题】:Determine return type based on input parameter根据输入参数确定返回类型
【发布时间】: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 &lt;typename T&gt; class Config {} 并使用 Config&lt;some_type&gt; instance; 对其进行实例化,然后使用 instance 进行处理,您无需指定任何内容。
  • 鲁道夫的回答正是我想要的。还是谢谢。

标签: c++ templates boost return-type


【解决方案1】:

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

在这里,您要么需要使模板参数显式化,要么使用返回代理类而不是实际对象的技巧,并定义隐式转换运算符。杂乱无章,大多数时候是不必要的。

【讨论】:

  • 噢噢噢……太棒了!我还没试过:D 谢谢一百万!
猜你喜欢
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-22
  • 2021-12-09
相关资源
最近更新 更多