views:

235

answers:

1

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)?

+8  A: 

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
+1 this looks hideous :)
Yuval A
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?
Polybos
@Niels, i forgot to wrap them in `var(..)`. Fixed :)
Johannes Schaub - litb
Polybos
@Niels, you need to cast. fixed
Johannes Schaub - litb
@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 ...
Polybos
+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).
caspin