Search code examples
c++templatesstd-functionstdbind

Is template type of a std::function detached by std::bind an undefined behavior?


i am working on MSVC

static bool filter_entity(void* entity)
{
    return entity == nullptr;
};
template<typename F>
static bool Dispatch(const F& filter)
{
    return filter(nullptr);
};
int main()
{
    void* ptr = new int();
    if (Dispatch(std::bind(&filter_entity, ptr))) cout << "nullptr" << endl;
    else cout << "intptr" << endl;
    //ret: intptr
}

it is weird that invoking a function with the const nullptr argument actually insert the ptr as argument, i wonder if it is an undefined behaviour.

Also is there a way to call filter() for this instance and make the template and std::bind significant for multiple situations?


Solution

  • From cppreference.com:

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

    The bound object from the question has no placeholders. So the nullptr in

    return filter(nullptr);
    

    is evaluated and discarded, and the result is the same as if

    return filter();
    

    was called. If we interpret the binding, this is the same as

    return filter_entity(ptr);
    

    (or would be if ptr was in scope). If you want to use the nullptr in the return statement, you would need to use std::placeholders::_1 in your std::bind.


    A followup question to this might be Why do objects returned from bind ignore extra arguments?