Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top