开发者

How to write a function that takes a functor as an argument

Basic开发者_Go百科ally I want to do this: Can I use a lambda function or std::function object in place of a function pointer?

clearly that is impossible for now for functions that expect a function pointer. However, it will work for a function that expects a functor ( I have done it before with stl's sort() function)

However, I don't know how to write a function that takes a functor as an argument!

Anyone?


I don't know how to write a function that takes a functor as an argument!

Since nobody has posted the std::function solution yet:

#include <functional>
#include <iostream>

void foo(std::function<int(int)> f)
{
    for (int i = 0; i < 10; ++i)
    {
        std::cout << f(i) << ' ';
    }
    std::cout << '\n';
}

int main()
{
    foo( [](int x) { return x*x; } );
}

You can use boost::function in pre C++11 compilers.


Just write the function to take an arbitrary type:

template <typename Func>
void foo(Func fun)
{
    fun(...);
}

This will then work with function pointers, functors and lambdas all the same.

void f() {}

struct G
{
    void operator()() {}
};

foo(&f);           // function pointer
foo(G());          // functor
foo([]() { ... }); // lambda


It has to be a template, like:

template<class F>
void foo( const F& f )
{
    f(x,y);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜