gpt4 book ai didi

c++ - 为什么可以将 std::bind 分配给参数不匹配的 std::function?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:21:13 24 4
gpt4 key购买 nike

我有如下代码:

#include <functional>
#include <iostream>
using namespace std;
void F(int x) {
cout << x << endl;
}
int main() {
std::function<void(int)> f1 = std::bind(F, std::placeholders::_1);
f1(100); // This works, will print 100.

int x = 0;
std::function<void()> f2 = std::bind(F, x);
f2(); // This works, will print 0.

std::function<void(int)> f3 = std::bind(F, x);
f3(200); // BUT WHY THIS WORKS?????? It prints 0.
return 0;
}

我的编译器信息是:Apple LLVM 版本 6.0 (clang-600.0.56)(基于 LLVM 3.5svn)目标:x86_64-apple-darwin13.4.0线程模型:posix

最佳答案

这是正确的行为。

std::bind 需要这种松散性 以适应它自己的规范。

考虑 std::placeholders,它用于标记传递给绑定(bind)函数的参数。

using std::placeholders;
std::function<void(int)> f2 = std::bind( F, _1 );
// Parameter 1 is passed to ^^
// the bound function.

f2(7); // The int 7 is passed on to F

同样,第二个参数是_2,第三个是_3,以此类推。

这提出了一个有趣的问题。这个函数对象应该如何表现?

auto f3 = std::bind( F, _3 );

正如您可能想象的那样,它遵循自己的 promise 将第三个参数传递给 F。这意味着它对前两个参数不做任何事情。

f3(10, 20, 30); // The int 30 is passed on to F. The rest?  Ignored.

所以这是预期的行为,并且可能是 std::bind 保留 lambda 的唯一“特征”,即使在 C++14 和 C++17 中也是如此。

std::bind 生成的对象旨在接受和忽略任何无关参数。

关于c++ - 为什么可以将 std::bind 分配给参数不匹配的 std::function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46578214/

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