用于方法链的c++ lambda表达式
C++ lambda expression for method chains
假设我有一个Car
对象,它也有一个Engine
成员,我想检查对象的属性,调用Car
上的一些方法和Engine
上的一些方法。要显式获取信息,我可以输入
cout << "my car has " << mycar.GetEngine().NCylinders() << " cylinders" << endl;
cout << "my car has " << mycar.NWheels() << " wheels" << endl;
所有这些调用的形式都是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 {return myEngine;}
private:
Engine myEngine;
};
int main(){
Car mycar;
map<string,function<double (const Car&)> > carinfos;
carinfos["cylinders"] = bind(&Engine::NCylinders,bind(&Car::GetEngine,_1));
carinfos["wheels"] = bind(&Car::NWheels,_1);
map<string,function<double (const Car&)> >::const_iterator info = carinfos.begin();
for(;info!=carinfos.end();++info){
cout << "my car has: " << (info->second)(mycar) << " " << info->first << endl;
}
return 0;
}
输出:
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
下面的代码,使用lambda而不是绑定,看起来并不太糟糕:
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";
}
}
循环可以用visit(c, v);
函数封装。
相关文章:
- 这 4 个 lambda 表达式之间有什么区别?
- 使用成员在类中创建 lambda 表达式
- 将 lambda 表达式传递给 std::function in C++
- 在 lambda 表达式中使用 std::atomic
- &&对lambda表达式有什么好处?
- Tbb 库:错误:编写自定义类函数而不是 lambda 表达式时,对函数的调用不匹配
- 列表.erase 中的 lambda 表达式
- 使用 lambda 表达式的 Raspbian G++ 8.3.0 导致 ']' 之前的预期主表达式 - 即使标准设置为 c++14
- 仅通过引用捕获的 lambda 表达式是否保证不会抛出?
- C++: priority_queue:模板参数中的 lambda 表达式
- 容器如何处理 lambda 表达式的参数
- 在C++ Lambda 表达式中,为什么人们更喜欢按值捕获而不是作为参数传递?
- 如何在 lambda 表达式中传递变量?
- 针对 std::function 的 lambda 表达式和模板推导:为什么会这样?
- 如何修改Lambda表达式以将输出放入文本文件
- C++如何使用lambda表达式来捕获上一次迭代的值
- 为什么Qt在信号和插槽中为lambda表达式抛出错误?
- C++:从捕获函数参数的函数返回 lambda 表达式
- C++ Lambda 表达式:通过 ref 开销捕获
- Qt 连接无法识别 lambda 表达式