C++ C++;方法链的lambda表达式

C++ C++;方法链的lambda表达式,c++,lambda,C++,Lambda,假设我有一个Car对象,它也有一个Engine成员,我想检查对象的属性,调用Car上的一些方法和Engine中的一些方法。要明确获取te信息,我可以 cout << "my car has " << mycar.GetEngine().NCylinders() << " cylinders" << endl; cout << "my car has " << mycar.NWheels() << " wheels

假设我有一个
Car
对象,它也有一个
Engine
成员,我想检查对象的属性,调用
Car
上的一些方法和
Engine
中的一些方法。要明确获取te信息,我可以

cout << "my car has " << mycar.GetEngine().NCylinders() << " cylinders" << endl;
cout << "my car has " << mycar.NWheels() << " wheels" << endl;
输出良好:

my car has: 12 cylinders
my car has: 4 wheels
<>但是嵌套的绑定可能会变得越来越丑陋,中间的链或方法必须有固定的参数,而我想知道是否有可能使用lambda表达式来解决,这可能导致一些类似于

的问题。
 //pseudocode
 carinfos["cylinders"]   = (_1.GetEngine().NCylinder());
 carinfos["wheels"]   = (_1.GetNWheel());
编辑:


@KennyTM和@Kerrek SB使用新的C++11 lambda表达式提供了极好的答案。我还不能使用C++11,因此我希望使用C++03提供类似简洁的解决方案。使用lambdas而不是binds,以下内容看起来并不可怕:

typedef std::map<std::string, std::function<int(Car const &)>> visitor;

int main()
{
  visitor v;
  v["wheels"]    = [](Car const & c) -> int { return c.NWheels(); };
  v["cylinders"] = [](Car const & c) -> int { return c.GetEngine().NCylinders(); };

  Car c;

  for (auto it = v.cbegin(), end = v.cend(); it != end; ++it)
  {
    std::cout << "My car has " << it->second(c) << " " << it->first << ".\n";
  }
}
typedef std::map visitor;
int main()
{
访客五;
v[“wheels”]=“carconst&c”->int{return c.NWheels();};
v[“气缸”]=[](汽车常数&c)->int{return c.GetEngine().ncylinds();};
c车;
for(auto it=v.cbegin(),end=v.cend();it!=end;++it)
{

std::cout可能是访问者模式?“轮子访问者,圆柱体访问者”…访问者的实现函数可以是lambda。是的,这可以工作,但我不能更改类的接口。在伪代码中,最后一行应该有“nwheel”,而不是“圆柱体”,对吗?如果你可以使用C++11,那么你可以使用真正的lambda。
[](const Car和Car){return Car.GetEngine().NCylinder();}
。顺便说一句,你确定要按值传递
car
吗?既然你说的是lambda,我想你想用c++11,如果是,那么Kenny TM的评论就行了。我想这是c++11的标准答案。+1个小旁注,在这个特殊的lambda中,它包含一个
返回
表达式,没有其他代码,return类型是可选的,因此可以拼写为:
[](Car const&c){return c.NWheels();}
typedef std::map<std::string, std::function<int(Car const &)>> visitor;

int main()
{
  visitor v;
  v["wheels"]    = [](Car const & c) -> int { return c.NWheels(); };
  v["cylinders"] = [](Car const & c) -> int { return c.GetEngine().NCylinders(); };

  Car c;

  for (auto it = v.cbegin(), end = v.cend(); it != end; ++it)
  {
    std::cout << "My car has " << it->second(c) << " " << it->first << ".\n";
  }
}