为什么在这种情况下std :: bind中需要占位符? [英] Why are placeholders required in std::bind in this case?

查看:283
本文介绍了为什么在这种情况下std :: bind中需要占位符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在回答

请看这个例子:

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

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

无法编译:

  prog.cpp:在函数'int main()':
prog.cpp:11:14:错误:没有匹配的调用'(std :: _ Bind< void (* const char *))(const char *,const char *)>)(const char [5])'
fn(1234);
^

如果我将代码更改为此,则效果很好:

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

输出为:

  asdf 
1234

为什么?我只有第一个参数。 std :: bind 不可能自动做placeholdering其他参数吗? (我期望在C ++ 98中 std :: bind1st 的结果相同。)为什么是

一般来说当使用 bind 时是不可能的,因为 func1 可能有默认参数,或重载具有不同数量的参数,或者可能是一个函数 operator()是一个函数模板, p>

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



在你的例子中明确,但我不知道如何容易地决定什么是明确的情况,用代码准确检测它们,并准确地在标准中定义它们。



bind1st 是明确的,因为它专门用于绑定一个2参数函数的第一个参数。


While answering this question, I see the following fact by accident.

Please see this example:

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

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

It is failed to compile it:

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");
              ^

If I change code into this, it works well:

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

Output is:

asdf
1234

Why? I bind only first argument.. Is it impossible that std::bind automatically do 'placeholdering' the other arguments? (I expected the same result of std::bind1st in C++98.) Why??

解决方案

In general when using bind it's not possible, because func1 might have default arguments, or overloads with different numbers of parameters, or might be a functor whose operator() is a function template that takes a parameter pack.

In such cases, there are many different ways to call func1. I think it's not desirable for bind to pick one and fill in the blanks with placeholders.

In your example it's unambiguous, but I'm not sure how easy it would be to decide what the unambiguous cases are, detect them accurately with code, and define them accurately in the standard.

bind1st was unambiguous by design, because it was specifically for binding the first parameter of a 2-parameter functor.

这篇关于为什么在这种情况下std :: bind中需要占位符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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