开发者

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 direc开发者_如何学Gotory 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


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); });


not1 accepts an instance of functor class, which should be an Adaptable Predicate (i.e. with typedefs for return value etc.), while you are trying to feed it with a function pointer. So you need to wrap it in a functor and ptr_fun might help. Perhaps this would work (assume using namespace std; using namespace boost;):

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


You need ptr_fun,

this rather elaborate illustration should print 1 three times: (see also http://ideone.com/C5HTR)

#include <functional>
#include <string>
#include <algorithm>
#include <iostream>

bool pred(const std::string& s)
{
    return s.size() % 2;
}

int main()
{
    std::string data[] = { "hello", "world!" };

    std::cout << std::count_if(data, data+2, 
            pred) << std::endl;

    std::cout << std::count_if(data, data+2, 
            std::ptr_fun(pred) ) << std::endl;

    std::cout << std::count_if(data, data+2, 
            std::not1(std::ptr_fun(pred))) << std::endl;

    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜