0

次のようなことができるようになりたい

std::map<EventType, boost::function<bool(int,int)>  callbackMap;
callbackMap[EVENT1] = boost::bind( magic_creator( this->m_isHerp && !this->m_isDerp ) , _1, _2 );

基本的に、true または false に評価される式を magic_creator に与えると、boost でバインドできる関数が返されます。したがって、上記の場合、magic_creator は _1 と _2 に関係なく true を返す関数を作成します。ラムダは役に立たないので使用できません。誰もこれのために何かを得ましたか?

PS callbackMap が何らかのクラスの一部であり、上記のコードの現在のスコープであると仮定します。

4

1 に答える 1

1

This is actually possible and not that ugly with either the Boost Lambda Library, Boost.Bind or Boost.Phoenix's bind.

All placeholders and binder types returned from a call to bind from any of those libraries will have all kinds of operators overloaded so you can easily create expressions with them "on the fly". With Boost.Bind:

#include <iostream>
#include <boost/bind.hpp>

struct X{ bool a, b; };

int main(){
  using boost::bind;
  auto op = bind(&X::a, _1) && !bind(&X::b, _1);
  X x{true, false};
  auto test = bind(op, x);
  if(test())
    std::cout << "Yay\n";
}

Live example.

This, of course, has the obvious disadvantage of going through member pointers. Also, in C++03, you had a mighty problem writing out the type of such a "lambda", since it's a huge templated mess. The little example above will yield a huge name, as can be seen here. And since a library solution was not "the best it could be", the standard committee added lambdas to the language. Yay.

Note that, while C++11's std::bind looks similar on the surface, it's a pure binder. It does not allow you to create expressions on-the-fly as it does not overload any operators for any related types.

于 2012-10-24T00:27:04.587 に答える