Why can I std::bind successfully with the wrong parameters?

Viewed 243
#include <iostream>
#include <functional>

using callback = std::function<void(int, void*)>;

void AddCallback(callback cb) {}

void foo(int i) {}

int main() {
  auto f = std::bind(&foo, std::placeholders::_1);
  AddCallback(f);
}

I tried the code with g++ 9.3.0 and clang++ 10.0.0, they both compiled ends no errors.

Is the type of bind result and callback the same type? One is std::function<void(int, void*)>, the other is something equal to std::function<void(int)>? Why can I call AddCallback() with different types?

2 Answers

It seems you can pass more arguments to the result of bind than necessary, and they will be silently ignored.

If some of the arguments that are supplied in the call to [the result of bind] are not matched by any placeholders ..., the unused arguments are evaluated and discarded.

— cppreference

it's not your AddCallback() whose accepting differnt type but it's type deduction whose creating confusing;

for example try to use

std::function<void(int)> f = std::bind(&foo, std::placeholders::_1);

or Addcallback function we will give you error

Error (active) E0312 no suitable user-defined conversion from "std::function<void (int)>" to "callback" exists

Related