小编luk*_*sen的帖子

方法链的C++ lambda表达式

假设我有一个Car也有Engine成员的对象,我想检查对象的属性,调用一些方法Car和一些方法Engine.为了明确地获取te信息,我可以做到

cout << "my car has " << mycar.GetEngine().NCylinders() << " cylinders" << endl;
cout << "my car has " << mycar.NWheels() << " wheels" << endl;
Run Code Online (Sandbox Code Playgroud)

所有这些电话都是这种形式mycar.<some method call chain here>.(您还可以假设它们都具有兼容的返回类型).我怎样才能有一个仿函数列表,以便我可以传递一个Car实例,它会相应地执行调用.

我<tr1/functional>使用嵌套绑定提出了一个解决方案.

#include <iostream>
#include <tr1/functional>
#include <map>

using namespace std;
using namespace std::tr1;
using namespace std::tr1::placeholders;

struct Engine{
    int NCylinders() const {return 12;}
};

struct Car{
    int    NWheels() const {return 4;}
    Engine GetEngine() const …
Run Code Online (Sandbox Code Playgroud)

c++ lambda

3
推荐指数
1
解决办法
938
查看次数

标签 统计

c++ ×1

lambda ×1