gpt4 book ai didi

C++11 绑定(bind) : difference between using and not-using placeholder

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:46:31 25 4
gpt4 key购买 nike

我有以下代码:

  1 #include <functional>
2 #include <iostream>
3
4 using namespace std::placeholders;
5
6 void update23(int i1, int &i2, int &i3)
7 {
8 i2 += i1;
9 i3 += i2;
10
11 std::cout << i2 << " " << i3 << std::endl;
12 }
13
19
20 int main()
21 {
22 int i1 = 10, i2 = 20, i3 = 30;
23
26 std::bind(update23, 10, 20, 30)();
27 std::bind(update23, 10, _1, _2)(20, 30);
28
29 return 0;
30 }

第 27 行编译失败。失败是有道理的,因为常量作为引用传递。

为什么第 26 行通过了?

我检查了 c++ 绑定(bind)源,但很快就迷路了。

如果您能引导我通过绑定(bind)源代码了解这里的神奇之处,将不胜感激!

最佳答案

像往常一样,您不能使用临时值调用需要可变左值引用(例如第二个 bind 表达式的结果)的函数。

第一个版本有效,因为绑定(bind)值按值捕获并作为左值提供给调用。

您可以更改函数签名或将调用更改为:

std::bind(update23, 10, _1, _2)(i2, i3);

关于C++11 绑定(bind) : difference between using and not-using placeholder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21353844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com