简体   繁体   English

C++11 中的 decltype(auto) - 推导返回类型

[英]decltype(auto) in C++11 - deducing return type

auto deduction of return types is possible in C++14 but I am trying to write something similar in C++11 ie在 C++14 中可以自动推导返回类型,但我正在尝试在 C++11 中编写类似的东西,即

If I were to write in C++14, it would be如果我用 C++14 编写,它会是

struct MyTypeA{
    std::vector<int> _d;
};

struct MyTypeB{
    int _id;
    std::string _name;
    MyTypeA _data;
};

decltype(auto) MakeObject(const MyTypeA& obj) {
    return std::make_tuple(obj._vec);
}

decltype(auto) MakeObject(const MyTypeB& obj) {
    return std::make_tuple(obj._id, obj._name, std::make_tuple(MakeObject(obj._data)));
}

The above is C++14 and I can rewrite MakeObject something similar in C++11 as below,上面是 C++14,我可以在 C++11 中重写MakeObject类似的东西,如下所示,

auto MakeObject (const MyTypeA& obj) -> decltype( std::make_tuple(obj._d)){
    return std::make_tuple(obj._d);
};

auto MakeObject (const MyTypeB& obj) -> decltype( std::make_tuple(obj._id, obj._name, std::make_tuple(MakeObject(obj._data)))){
    return std::make_tuple(obj._id, obj._name, std::make_tuple(MakeObject(obj._data)));
};

And as you can see I have a bunch of overloaded non-member functions.正如你所看到的,我有一堆重载的非成员函数。 Though this works, it seems very verbose and redundant code.虽然这有效,但它似乎非常冗长和冗余的代码。 Is there a better way to do this in C++11?在 C++11 中是否有更好的方法来做到这一点?

Is there a better way to do this in C++11?在 C++11 中是否有更好的方法来做到这一点?

While return type of a regular function cannot be deduced prior to C++14, the return type of lambda can.虽然在 C++14 之前无法推导出常规函数的返回类型,但 lambda 的返回类型可以。 And a non-capturing lambda behaves much like a function.一个非捕获 lambda 的行为很像一个函数。 So, in C++11 you could do所以,在 C++11 中你可以做

auto MakeObject = [](const MyTypeA& obj) {
     return std::make_tuple(obj._vec);
}

However, this doesn't allow for overloading, which you use.但是,这不允许您使用的重载。 If you need overloading, then the trailing decltype may be a better choice.如果您需要重载,那么尾随 decltype 可能是更好的选择。

#define RETURNS(...) decltype(__VA_ARGS__) { return __VA_ARGS__; }

Then you get然后你得到

auto MakeObject(const MyTypeA& obj)
->RETURNS(std::make_tuple(obj._vec))

This may or may not be considered better.这可能会也可能不会被认为更好。 But it does remove the DRY violation.但它确实消除了 DRY 违规。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM