从函数返回多个值的优雅方法 [英] Elegant ways to return multiple values from a function

查看:104
本文介绍了从函数返回多个值的优雅方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数主流编程语言中,从函数返回多个值是非常尴尬的事情。

典型的解决方案是创建一个 struct 或一个普通的旧数据 class ,并返回或返回通过引用或指针传递至少一些参数,而不是返回它们。

使用引用/指针是非常尴尬的,因为它依赖于副作用并且意味着您还有另一个参数可以传递。

类/结构解决方案也是恕我直言,很尴尬,因为你最终会得到一百万个小类/结构,它们只用于从函数返回值,产生不必要的混乱和冗长。

此外,很多时候总是需要一个返回值,其余的只在某些情况下由调用者使用。这两种解决方案都不允许调用者忽略不需要的返回类型。



我知道的一种语言可以很好地处理多个返回值,它是Python。对于那些不熟悉的人来说,它使用元组拆包:

  a,b = foo(c)#a和b是常规变量。 
myTuple = foo(c)#myTuple是(a,b)的元组

有没有人有任何其他解决这个问题的好方法?除了Python以外,现有主流语言中的两种习惯用法以及您在非主流语言中看到的语言级别解决方案都是受欢迎的。

解决方案

<几乎所有受ML影响的函数语言(大部分都是这样)也有很好的元组支持,使得这种事情变得微不足道。

对于C ++,我喜欢boost :: tuple加boost :: tie(或者std :: tr1,如果有的话)

  typedef boost :: tuple< double ,双,双> XYZ; 

XYZ foo();

double x,y,z;
boost :: tie(x,y,z)= foo();

或不太人为的例子

  MyMultimap :: iterator lower,upper; 
boost :: tie(lower,upper)= some_map.equal_range(key);


It seems like in most mainstream programming languages, returning multiple values from a function is an extremely awkward thing.

The typical solutions are to make either a struct or a plain old data class and return that, or to pass at least some of the parameters by reference or pointer instead of returning them.

Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass.

The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity.

Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.

The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:

a, b = foo(c)  # a and b are regular variables.
myTuple = foo(c)  # myTuple is a tuple of (a, b)

Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.

解决方案

Pretty much all ML-influenced functional langues (which is most of them) also have great tuple support that makes this sort of thing trivial.

For C++ I like boost::tuple plus boost::tie (or std::tr1 if you have it)

typedef boost::tuple<double,double,double> XYZ;

XYZ foo();

double x,y,z;
boost::tie(x,y,z) = foo();

or a less contrived example

MyMultimap::iterator lower,upper;
boost::tie(lower,upper) = some_map.equal_range(key);

这篇关于从函数返回多个值的优雅方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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