在C ++ 11中省略返回类型 [英] Omit return type in C++11

查看:111
本文介绍了在C ++ 11中省略返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现自己在C ++ 11模式下使用gcc 4.5的以下宏:

I've recently found myself using the following macro with gcc 4.5 in C++11 mode:

#define RETURN(x) -> decltype(x) { return x; }

并编写如下函数:

template <class T>
auto f(T&& x) RETURN (( g(h(std::forward<T>(x))) ))

我一直这样做,以避免不必要的有效地写函数体两次,并保持身体和返回类型同步更改(在我看来是一个灾难等待发生)。

I've been doing this to avoid the inconvenience having to effectively write the function body twice, and having keep changes in the body and the return type in sync (which in my opinion is a disaster waiting to happen).

问题是这种技术只适用于一个行函数。所以当我有这样的东西(令人讨厌的例子):

The problem is that this technique only works on one line functions. So when I have something like this (convoluted example):

template <class T>
auto f(T&& x) -> ...
{
   auto y1 = f(x);
   auto y2 = h(y1, g1(x));
   auto y3 = h(y1, g2(x));
   if (y1) { ++y3; }
   return h2(y2, y3);
}

然后我必须在返回类型中加入一些可怕的东西。

Then I have to put something horrible in the return type.

此外,每当我更新函数,我将需要更改返回类型,如果我不更改正确,我会得到一个编译错误,如果我幸运的,或者在更糟的情况下的运行时bug。必须将更改复制并粘贴到两个位置并保持同步我感觉不是好的做法。

Furthermore, whenever I update the function, I'll need to change the return type, and if I don't change it correctly, I'll get a compile error if I'm lucky, or a runtime bug in the worse case. Having to copy and paste changes to two locations and keep them in sync I feel is not good practice.

我不能想到一个情况,我想要一个隐式转换返回而不是一个显式转换。

And I can't think of a situation where I'd want an implicit cast on return instead of an explicit cast.

当然有一种方法要求编译器推断这个信息。编译器保持它的秘密是什么?我认为C ++ 11的设计是不需要这样的重复。

Surely there is a way to ask the compiler to deduce this information. What is the point of the compiler keeping it a secret? I thought C++11 was designed so such duplication would not be required.

推荐答案

看起来g++ 4.8 正在获得自动返回类型扣除的实现。
这个补丁是由Jason Merrill放入的,他也为C ++ - 1Y发送了一个论文。此功能可以使用-std = c ++ 1y。

It would appear that g++ 4.8 is getting an implementation of auto return type deduction. The patch was put in by Jason Merrill who is also sending a paper for C++-1Y for the feature. The feature is available with -std=c++1y.

仍在使用它。

这篇关于在C ++ 11中省略返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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