Search code examples
c++boostc++11negate

Negate boost is_directory in std algorithm


boost::filesystem::recursive_directory_iterator end, begin(directory);

auto num_of_files=std::count_if(begin, end, 
        std::not1(boost::filesystem::is_directory)));

I am trying to negate the function is_directory on the above directory iterator but am hitting a brick wall. I have tried specifying the template for not1 as bool(*)(const boost::filesystem::path&) and tried static casting the function both without success.

I know I can resort to a lamdba but this is cleaner if it works.

Thanks


Solution

  • std::not1 needs a function object as its argument. This function object can be obtained with std::ptr_fun, so this should work:

    auto num_of_files=std::count_if(begin, end, 
            std::not1(std::ptr_fun((bool(*)(const boost::filesystem::path&))boost::filesystem::is_directory)));
    

    (the number of parentheses is probably incorrect). BTW, you need the cast because is_directory is an overloaded function.

    However, since you tag you question c++11, you could use lambdas:

    auto num_of_files=std::count_if(begin, end, [](const boost::filesystem::path& p) { return !boost::filesystem::is_directory(p); });