Question

If this question has been asked, I apologize.

I thought you couldn't bind functions with a different signature, but look at this:

void TakesChar(char parameter)
{
    std::cout << parameter << std::endl;
}

using CallSig = void(float);
using CallBack = std::function<CallSig>;

int main()
{
    CallBack callback = std::bind(&TakesChar, std::placeholders::_1);
    callback(1.1f);
    callback(2.2f);

    return 0;
}

That compiles and runs. You can try different parameter types and numbers. You can, for instance, modify TakesChar so that it takes no parameters, and it will still compile.

Why is this? Is there a rationale behind it? And can I enforce signatures to match exactly?

Thanks.

Was it helpful?

Solution

Actually, there are two questions here:

  1. Why is conversion allowed ?
  2. Why if no argument is provided to bind, the return object accepts any number of argument ?

The former is just a decision on the behavior of bind: since you can call TakesChar(1.1f) why not allow std::bind(&TakesChar, _1) to bind to std::function<void(float)> ? The committee decided to allow it.

The latter, as explained in comments, was already addressed on SO. In short, not only is it easier, it also allows to bind an object that has multiple operator() of different arities.

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