10

Consider the following piece of C++0x code:

a_signal.connect([](int i) {
  if(boost::any_cast<std::string>(_buffer[i]) == "foo")
  {
    base_class<>* an_object = new derived_class();
    an_object->a_method(_buffer[i]);
  }});

How would it correctly look in Boost Lambda (since this C++0x feature can't be used in GCC 4.4 yet)?

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
Karl von Moor
  • 8,484
  • 4
  • 40
  • 52

1 Answers1

11

I think this should work:

a_signal.connect(if_then(
                  bind((std::string(*)(any&))&any_cast, var(_buffer)[_1]) == "foo",
                   bind(&base_class<>::a_method, 
                    ll_static_cast< base_class<>* >(
                     new_ptr<derived_class>()
                    ), 
                    var(_buffer)[_1]
                   )
                 )
);

bind, if_then, ll_static_cast, new_ptr, _1, var (and, i think ref too) are members of boost::lambda.

But honestly, i would refuse to work with such code, personally :)

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • thanks. I'll be really happy if I can use C++0x fully :). With your solution I get `no match for operator[]` in the lines where `_buffer[_1]` is called .. but the `operator[]` exists in the buffer class. Do you have an idea how to solve it? – Karl von Moor May 13 '10 at 12:27
  • @Niels, i forgot to wrap them in `var(..)`. Fixed :) – Johannes Schaub - litb May 13 '10 at 12:28
  • Now In the line `boost::bind(&any_cast, boost::ref(var(_buffer)[lambda::_1])) == "foo"`, I get a no matching function call for `bind(, const boost::reference_wrapper ...`. I have `boost/lambda/bind.hpp` included and the other bind call doesn't fail ... – Karl von Moor May 13 '10 at 13:29
  • @Niels, you need to cast. fixed – Johannes Schaub - litb May 13 '10 at 13:35
  • @Johannes Schaub: It slowly becomes embarrasing for me ... no it says no matching function call for `if_then`. But `boost/lambda/if.hpp` is included ... – Karl von Moor May 13 '10 at 13:45
  • 1
    +1 for refusal to work with such code. I agree, it's not just that I wouldn't write code like that, I would never allow code like that through a code review (unless of course I was overruled, but you get the point). – deft_code May 13 '10 at 16:30