c++null-pointer

Is there a std:: function which is usable as a predicate (similar to std::is_null_ptr)?


I had hoped for a short, concise, elegant:

std::array<int*,10> ip_arr;
bool all_null = std::all_of(ip_arr.begin(),ip_arr.end(),std::is_null_ptr_as_fn);

instead of inventing a lambda for that purpose:

std::array<int*,10> ip_arr;
bool all_null = std::all_of(ip_arr.begin(),ip_arr.end(),[](int *ip){ return ip == nullptr;});

which may even be suspicious because I ignored std::is_null_ptr and instead it should read like:

std::array<int*,10> ip_arr;
bool all_null = std::all_of(ip_arr.begin(),ip_arr.end(),[](int *ip){ std::is_null_ptr r(ip); return r();});

Yuck.


Solution

  • The standard library provides several function objects for arithmetic and logical operations: https://en.cppreference.com/w/cpp/utility/functional

    You can use logical_not to detect pointer null-ness.

    bool all_null = std::all_of(ip_arr.begin(), ip_arr.end(), std::logical_not{});
    

    Note that we're passing an instance of the function object (using {} or () to instance it).


    As indicated by other answers and comments however, the lambda in your second code snippet might be considered more readable, with clearer intent, without relying on implicit pointer-to-bool conversion.

    If you're seeking conciseness for this, or any other lambda predicate, you could name it for re-use:

    auto is_null = [](auto *t) { return t == nullptr; };
    
    bool all_null = std::all_of(ip_arr.begin(), ip_arr.end(), is_null);
    

    or composition with other function objects:

    bool all_null = std::none_of(ip_arr.begin(), ip_arr.end(), std::not_fn(is_null));