使用lambda函数定义非常小的辅助函数是否很好?

use*_*963 7 c++ lambda coding-style c++11

作为一个愚蠢的例子,假设我有一个函数int f(vector<int> v),由于某种原因,我需要v多次执行几个操作f.而不是在其他地方放置辅助函数(这可能会增加混乱并损害可读性),做这样的事情有哪些优点和缺点(效率,可读性,可维护性等):

int f(vector<int> v)
{
    auto make_unique  = [](vector<int> &v)
    {
        sort(begin(v), end(v));
        auto unique_end = unique(begin(v), end(v));
        v.erase(unique_end, end(v));
    };
    auto print_vector = [](vector<int> const &v)
    {
        copy(begin(v), end(v), ostream_iterator<int>(cout, " "));
        cout << endl;
    };

   make_unique (v);
   print_vector(v);
   // And then the function uses these helpers a few more times to justify making
   // functions...
}
Run Code Online (Sandbox Code Playgroud)

还是有一些首选的选择?

Jon*_*rdy 7

这种本地范围的函数的优点是它们不会用"辅助"定义污染周围的代码 - 所有行为都可以限制在单个范围内.由于它们可以访问周围函数的词法范围,因此它们可用于在不传递许多参数的情况下对行为进行因子分析.

您还可以使用它们创建小型DSL来抽象函数的机械细节,以便以后更改它们.您可以为重复值定义常量; 为什么不对代码做同样的事情?

举个简单的例子,一个状态机:

vector<int> results;
int current;
enum { NORMAL, SPECIAL } state = NORMAL;

auto input = [&]{ return stream >> current; }
auto output = [&](int i) { results.push_back(i); };
auto normal = [&]{ state = NORMAL; };
auto special = [&]{ state = SPECIAL; };

while (input()) {
    switch (state) {
    case NORMAL:
        if (is_special(current)) special(); else output(current);
        break;
    case SPECIAL:
        if (is_normal(current)) normal();
        break;
    }
}

return results;
Run Code Online (Sandbox Code Playgroud)

缺点是您可能会不必要地隐藏和专门化对其他定义有用的泛型函数.A uniquifyprint_vector函数值得浮出并重复使用.