根据输入参数确定退货类型 [英] Determine return type based on input parameter

查看:77
本文介绍了根据输入参数确定退货类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to implement a generic configuration file parser and I'm wondering how to write a method in my class that is able to determine its return type, based on the type of an input parameter. Here's what I mean:

class Config
{
    ...
    template <typename T>
    T GetData (const std::string &key, const T &defaultValue) const;
    ...
}

为了调用上述方法,我必须使用类似这样的东西:

In order to call the above method, I have to use something like this:

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

如何摆脱冗余规范?我看到boost :: property_tree :: ptree :: get()可以做到这一点,但是实现起来相当复杂,我无法解读这个复杂的声明:

How can I get rid of the redundant specification? I saw that boost::property_tree::ptree::get() is able to do this trick, but the implementation is rather complicated and I wasn't able to decipher this complex declaration:

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的依赖.

If possible, I would like to do this, without creating a dependency on boost in the code that will use my Config class.

PS:关于C ++模板,我是n00b:(

PS: I'm a n00b when it comes to C++ templates :(

推荐答案

您显示的代码中的enable_if无关紧要.在您的情况下,您只需删除显式模板规范,编译器将从参数中推断出它:

The enable_if in the code you’ve shown does something unrelated. In your case, you can just remove the explicit template specification, the compiler will infer it from the parameter:

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

更好的是,在C ++ 11中,您甚至不需要在声明时指定变量类型,也可以对其进行推断:

Even better, in C++11 you don’t even need to specify the variable type at declaration, it can be inferred as well:

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

…但是请注意,C ++只能从参数推断模板参数,而不能从返回类型推断.也就是说,以下起作用:

… but note that C++ can only infer template arguments from parameters, not the return type. That is, the following does not work:

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

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

在这里,您需要使模板参数明确,或者使用一种技巧来返回代理类而不是实际对象,并定义一个隐式转换运算符.杂乱无章,大部分时间都是不必要的.

Here, you’d either need to make the template argument explicit, or use a trick that returns a proxy class rather than the actual object, and defines an implicit conversion operator. Messy and most of the time unnecessary.

这篇关于根据输入参数确定退货类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆