Search code examples
c++stdbind

Why does std::bind statically type check arguments passed to the function?


Not exactly a question but more of a musing... I wrote a program to test how 'std::bind' passes arguments to the function being binded. It seems like in this instance the C++ compiler performs static type checking:

#include <iostream>
#include <functional>

void take_int(const int *a)
{
    if (a)
    {
        std::cout << "a is " << *a << std::endl;
    }
    else
    {
        std::cout << "null" << std::endl;
    }
}

int main()
{
    int *a = new(int);
    *a = 4;
    take_int(NULL); //prints 'null'
    auto fn = std::bind(take_int, NULL); //fails to compile
    fn();
    return 0;
}

It seems inconsistent to be able to directly call the function with NULL but for it to fail at compile time when doing so through std::bind.

I guess std::bind is using more modern C++ features which chooses to enforce this?


Solution

  • Your Compiler defines NULL as 0 which as a literal can be implicitly converted to an int*. Thats why your first call is succesful. But std::bind() will generate an object for <void (&)(const int *),int> which can't be called since a variable of type int cannot be implicitly converted to int*.