为什么在这种情况下std::bind中需要占位符

Why are placeholders required in std::bind in this case?

本文关键字:占位符 bind 这种情况下 std 为什么      更新时间:2023-10-16

在回答这个问题时,我意外地看到了以下事实。

请看这个例子:

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

为什么I仅绑定第一个参数。。std::bind是否不可能自动对其他参数执行占位符操作?(我希望std::bind1st在C++98中也能得到同样的结果。)为什么??

通常在使用bind时,这是不可能的,因为func1可能有默认参数,或者重载了不同数量的参数,或者可能是一个函数,其operator()是一个采用参数包的函数模板。

在这种情况下,有许多不同的方法来调用func1。我认为bind不希望选择一个并用占位符填空。

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

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