大家对使用lambdas在C++中做嵌套函数有什么看法?例如,而不是这样:
static void prepare_eggs()
{
...
}
static void prepare_ham()
{
...
}
static void prepare_cheese()
{
...
}
static fry_ingredients()
{
...
}
void make_omlette()
{
prepare_eggs();
prepare_ham();
prepare_cheese();
fry_ingredients();
}
Run Code Online (Sandbox Code Playgroud)
你做这个:
void make_omlette()
{
auto prepare_eggs = [&]()
{
...
};
auto prepare_ham = [&]()
{
...
};
auto prepare_cheese = [&]()
{
...
};
auto fry_ingredients = [&]()
{
...
};
prepare_eggs();
prepare_ham();
prepare_cheese();
fry_ingredients();
}
Run Code Online (Sandbox Code Playgroud)
来自通过使用Pascal学习如何编码的一代,嵌套函数对我来说非常有意义.但是,在代码审查期间,这种用法似乎让我工作组中一些经验不足的开发人员感到困惑,因为我以这种方式使用了lambdas.
我有以下内容:
typedef std::function<bool (const std::string&)> SomethingCoolCb;
class ClassA
{
public:
void OnSomethingCool(const SomethingCoolCb& cb)
{
_cb = cb;
}
private:
SomethingCoolCb _cb;
};
class ClassB
{
public:
ClassB();
bool Juggle(const std::string& arg);
private:
ClassA _obj;
};
Run Code Online (Sandbox Code Playgroud)
我想指定ClassB :: Juggle()成员函数作为ClassB :: _ obj的回调.在C++ 11中这样做的正确方法是(在ClassB的构造函数中):
ClassB::ClassB()
{
_obj.OnDoSomethingCool(
[&](const std::string& arg) -> bool
{
return Juggle(arg);
});
}
Run Code Online (Sandbox Code Playgroud)
据我所知,编译器将使用上面的lambda代码生成一个std :: function对象.因此,当调用回调时,它将调用std :: function :: operator()成员,然后它将调用ClassB :: Juggle()而不是直接调用ClassB :: Juggle().除非我误解了封面下发生的事情,否则一切似乎都有点低效.有没有更好的办法?
我应该按值还是按 const 引用将 boost::python::object 对象传递给 C++ 函数?我几乎总是通过 const 引用传递 C++ 中的重要对象。然而,在 Boost Python 文档示例中,它们总是按值传递 boost::python::object 。所以我想知道这背后是否有原因,或者他们这样做只是为了让文本更容易阅读或其他什么。