Search code examples
c++11lambdafunctor

How can I properly re-write C++11 lambda expression without lambda expr


I have a following code:

class Variant
{
public:
    void init();
}

void Variant::init()
{
    int var 1;
    vector list;
    vector list2;

    tbb::parallel_for(tbb::blocked_range<std::size_t>(0, list.size(), ClrSize),
    [this, &var1, &list,&list2](const tbb::blocked_range<std::size_t> &range)
    {
        /*some code here*/
    }

I thought about implementing operator()(const tbb::blocked_range<std::size_t> &range)

class Variant
{
public:
    void operator()(const tbb::blocked_range<std::size_t> &range)
    {
        /*some code here*/
    }
    void init();
}

void Variant::init()
{
    int var 1;
    vector list;
    vector list2;

    tbb::parallel_for(tbb::blocked_range<std::size_t>(0, list.size(), ClrSize), this);
}

but it doesn't solve capture list problem.

How I can re-write lambda expression? What can I do with var1, list, list2 arguments?

Thanks


Solution

  • You capture in the constructor of the functor you're making, and pass the capture variables as arguments to the constructor. It's easiest to use a separate class, rather than trying to reuse the object you exist in.

    class MyFunctor
    {
        Variant& x; int& y; vector& z; vector& foo;
    public:
        MyFunctor(Variant& x, int& y, vector& z, vector& foo) : x(x), y(y), z(z), foo(foo) {};
        void operator()(const tbb::blocked_range<std::size_t> &range)
        {
            /* use x, y, z and foo here */
        }
    }
    

    then have init make an instance of MyFunctor to pass.