为什么这个“min” cpp-next的故障模板? [英] Why is this "min" template of cpp-next at fault?

查看:103
本文介绍了为什么这个“min” cpp-next的故障模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读 cpp-next ,其中 min 模板作为如何将详细的C ++代码与python代码进行比较的示例。

I was reading cpp-next where this min template is presented as an example of how verbose C++ code can be compared to python code

template <class T, class U>
auto min(T x, U y)->decltype(x < y ? x : y)
{ return x < y ? x : y; }

起初这看起来很无辜,但Daveed Vandevoorde做了这个话。

At first this looks innocent but Daveed Vandevoorde made this remark


在返回类型规范中使用decltype的最小模板不工作:它返回一个引用(因为参数是一个左值),最后引用一个局部变量最常见的用途。

The min template that uses decltype in its return type specification doesn’t work: It returns a reference (because the argument is an lvalue) that ends up referring to a local variable in most common uses.

我想这可能不清楚每个人问题如何显现。你能给出详细的解释和可能的修正吗?

I figured it may not be clear to everyone how the problem manifests. Can you please give a detailed explanation and possible fixes?

推荐答案

问题是参数不作为参考。这在多态类型的情况下调用切片,然后引用返回局部变量。解决方案是将参数作为右值引用,调用完美转发,然后简单地推导并返回返回类型。完成后,返回引用就是很好,因为值仍然存在。

The problem is that the arguments aren't taken as references. This invokes slicing, in the case of polymorphic types, and then a reference return to local variable. The solution is to take the arguments as rvalue references, invoking perfect forwarding, and then simply deduce and return the return type. When this is done, returning a reference is just fine, as the value still exists.

这篇关于为什么这个“min” cpp-next的故障模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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