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

北慕城南 提交于 2019-12-24 04:44:09

问题


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??


回答1:


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.



来源:https://stackoverflow.com/questions/22934338/why-are-placeholders-required-in-stdbind-in-this-case

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!