1

This is follow up on another question that I had a while ago boost variant simple call to common methods.

Thanks to the suggested idea there I can do

boost::apply_visitor([](auto const& obj) { obj.some_operation(); }, variant);

I extended the idea and now I have:

auto visitor = [](auto const& element) { return element->do_something(); };

as a global variable and the visiting it is simply:

boost::apply_visitor(visitor, variant);

My question is how I can extend this pattern if possible to be able to use it for lambdas that accept additional arguments. Say if I have:

auto visitor = [](auto const& element, int a) { return element->do_something(a); };

boost::apply_visitor(<some visitor magic with passing a>, variant);

Note that at the time the lambda is defined there is nothing to capture there.

Community
  • 1
  • 1
gsf
  • 6,612
  • 7
  • 35
  • 64
  • I don't see the difference between your previous question and this question... The answer is exactly the same. Can you help? – Rakete1111 Jun 08 '16 at 03:53
  • The first question is how I can apply the same code to all types. This question is about passing arguments. – gsf Jun 08 '16 at 04:09
  • Not really. You ask how to pass an extra parameter when using `boost::apply_visitor`, same as here – Rakete1111 Jun 08 '16 at 04:13
  • oops, sorry, it seems I pasted link to somebodies else question - the question is fixed now – gsf Jun 08 '16 at 04:47

1 Answers1

1

Note that at the time the lambda is defined there is nothing to capture there.

You may define it later, or define an other one at moment of the call:

auto visitor = [](auto const& element, int a) { return element->do_something(a); };

// ... with possible usage of visitor

const int b = ...;
boost::apply_visitor([&](auto const& element) {visitor(element, b);}, variant);
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • These are good options, but I finished having a full flavoured visitor class that accepts the arguments in the constructor that allows me to do `boost::apply_visitor(visitor(b), variant);`. Note that reusing the implementation is easy to do with a template method. I was just suffering from the 'if all you have is a hammer, everything looks like a nail' syndrome for a while. – gsf Jun 08 '16 at 16:59