Home > Software engineering >  create lambda signature after template argument
create lambda signature after template argument

Time:12-04

I need to write a function (f) that accepts a std::function (g) with a generic callback parameter. In the function f, some additional code should be executed when the callback is called. I would therefore need to create a lambda with a signature depending on the generic callback parameter. My template skills fails me here.

So basically, in the snippet below, both g1 and g2 should be possible to use as input to f:

void g1(std::function<void()> cb)
{
  // do stuff, call callback
  cb();
}

void g2(std::function<void(int)> cb)
{
  cb(1);
}

template<typename TFunc, typename TCb>
void f(TFunc g, TCb handler)
{
  // in some way intercept the callback from g to do additional stuff when callback arrives
  g([handler](int i) {  // this only works for g2 now, needs to be generic
    // Do the extra stuff here before calling final callback

    // Call final callback with same signature as g1 (or g2) callback
    handler(i);
  });
}

void main()
{
  f(g1, [](){});
  f(g2, [](int){});
}

CodePudding user response:

I'm not sure if this is what you need, but maybe you can use it as a starting point... This requires C 14

  g([handler](auto&&... args ) {  
    // Do the extra stuff here before calling final callback

    // Call final callback with same signature as g1 (or g2) callback
    handler(std::forward<decltype(args)>(args)...);
  });

Full example here: https://godbolt.org/z/xranbfrEE

If you can use C 20, you can use the new lambda template parameters:

  g([handler]<typename... Args> (Args&&... args ) {  
    handler(std::forward<Args>(args)...);
  });
  •  Tags:  
  • c
  • Related