按值传递到引用参数 [英] Passing to a Reference Argument by Value

查看:193
本文介绍了按值传递到引用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个简单的程序:

vector<int> foo = {0, 42, 0, 42, 0, 42};
replace(begin(foo), end(foo), foo.front(), 13);

for(const auto& i : foo) cout << i << '\t';

当我写它时,我希望得到:

When I wrote it I expected to get:


13 42 13 42 13 42

13 42 13 42 13 42

但我得到:


13 42 0 42 0 42

13 42 0 42 0 42

问题当然是 replace 通过引用接收最后2个参数。因此,如果它们中的任何一个恰巧在对结果进行操作的范围内可能是意想不到的。我可以通过添加一个临时变量来解决这个问题:

The problem of course is that replace takes in the last 2 parameters by reference. So if either of them happen to be in the range being operated on the results may be unexpected. I can solve this by adding a temporary variable:

vector<int> foo = {0, 42, 0, 42, 0, 42};
const auto temp = foo.front();
replace(begin(foo), end(foo), temp, 13);

for(const auto& i : foo) cout << i << '\t';

我知道C ++ 11给了我们各种类型的工具是可能的

I do know that C++11 gave us all kinds of type tools is it possible that I could simply force this value to a non-reference type and pass that inline, without creating the temporary?

推荐答案

解决方案可以是一个非引用类型,

A solution could be as follows (even though you are making a temporary)

template<class T>
void replace_value_of_first(std::vector<T>& v, const T& value)
{
    std::replace(v.begin(), v.end(), T(v.front()), value);
}

这篇关于按值传递到引用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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