How to handle lambdas in a pre-lambda compiler

I have code that can be greatly reduced in complexity using lambdas. However, unfortunately, we must use a compiler that does not fully support C ++ 11, and we cannot switch easily. Now the question is how to bring the logic as close as possible to a lambda expression with inaccessible functions (i.e. std::function, lambdas - no).

The usual solution is to define a functor somewhere else, and then use it in the appropriate place:

struct functor{
   functor( type & member ) : m_member( member ) {}
   void operator()( ... ) {...}
   type & m_member;
};

void function() {
   use_functor( functor(...) );
}

I am very used to this template, although I really don't like it. The main reason for not defining a class is usually because I will use the functor in STL, and templates do not like the structures defined in the function line. However, in my case, the function use_functor()will be a normal method, so I can define a functor inside the function itself (each functor is used in only one function).

void function() {
   struct functor{
      functor( type & member ) : m_member( member ) {}
      void operator()( ... ) {...}
      type & m_member;
   };
   use_functor( functor(...) );
}

This seems a bit improved, but still requires much more ugly code that I would like. For example, I would like to completely get rid of the name of the functor. I know that you can create an anonymous structure if I use only one value.

void function() {
   struct{
      // functor( type member ) : m_member( member ) {}
      void operator()( ... ) {...}
      // type & m_member;
   } callback ;
   use_functor( callback );
}

, . , . , , , .

, , , , .

?

+5
3

- struct , :

void function() {
   type the_thing;
   struct {
      void operator()( ... ) {...}
      type & m_member;
   } callback = {the_thing};
   use_functor( callback );
}

type & m_member callback.

+1

awoodland:

#define MY_LAMBDA(name, memberType, memberValue, body) \
    struct {                                     \
        void operator()( ... ) body              \
        memberType & memberValue;                   \
    } name = {memberValue}

void function() {
    type thing_to_capture;

    MY_LAMBDA(callback, type, thing_to_capture
    {
        std::cout << thing_to_capture << std::endl;
    });

    use_functor( callback );
}

MY_LAMBDA , . , , " "

, , , :

void function() {
    type thing_to_capture;

    auto callback = [&thing_to_capture]()
    {
        std::cout << thing_to_capture << std::endl;
    };

    use_functor( callback );
}
0

You can try to increase the lambda library or boost :: phoenix . They are both designed to perform lambda style operations without actually supporting lambda. Because they are template-based, errors can be difficult to debug when something is not working properly.

0
source

All Articles