Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

create lambda signature after template argument

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)...);
  });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading