gpt4 book ai didi

c++ - 为什么在这种情况下 std::bind 需要占位符?

转载 作者:搜寻专家 更新时间:2023-10-31 01:44:53 25 4
gpt4 key购买 nike

在回答 this question 时, 我无意中看到了以下事实。

请看这个例子:

void func1(const char *str1, const char *str2) { puts(str1); puts(str2); }
...

auto fn = std::bind(func1, "asdf");
fn("1234");

编译失败:

prog.cpp: In function ‘int main()’:
prog.cpp:11:14: error: no match for call to ‘(std::_Bind<void (*(const char*))(const char*, const char*)>) (const char [5])’
fn("1234");
^

如果我将代码改成这样,它运行良好:

    auto fn = std::bind(func1, "asdf", _1);

输出是:

asdf
1234

为什么?我只绑定(bind)第一个参数。std::bind 不可能自动“占位”其他参数吗? (我期望 C++98 中的 std::bind1st 有相同的结果。)为什么??

最佳答案

一般当使用 bind 时这是不可能的,因为 func1 可能有默认参数,或者有不同数量的参数重载,或者可能是一个仿函数,其 operator() 是一个接受参数包的函数模板。

在这种情况下,有许多不同的方法可以调用func1。我认为 bind 选择一个并用占位符填充空白是不可取的。

在您的示例中,它是明确的,但我不确定确定明确的情况是什么、使用代码准确检测它们并在标准中准确定义它们有多容易。

bind1st 在设计上是明确的,因为它专门用于绑定(bind) 2 参数仿函数的第一个参数。

关于c++ - 为什么在这种情况下 std::bind 需要占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22934338/

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