如何在C ++中定义匿名函数?

时间:2012-09-18 19:33:44

标签: c++ function syntax inline

我可以用C ++内联定义函数吗?我不是在讨论lambda函数,而是讨论导致编译器优化的inline关键字。

4 个答案:

答案 0 :(得分:55)

C ++ 11在该语言中添加了lambda functions。以前版本的语言(C ++ 98和C ++ 03)以及所有当前版本的C语言(C89,C99和C11)都不支持此功能。语法如下:

[capture](parameters)->return-type{body}

例如,要计算向量中所有元素的总和:

std::vector<int> some_list;
int total = 0;
for (int i=0;i<5;i++) some_list.push_back(i);
std::for_each(begin(some_list), end(some_list), [&total](int x) {
  total += x;
});

答案 1 :(得分:23)

在C ++ 11中,您可以使用闭包:

void foo()
{
   auto f = [](int a, int b) -> int { return a + b; };

   auto n = f(1, 2);
}

在此之前,您可以使用本地类:

void bar()
{
   struct LocalClass
   {
       int operator()(int a, int b) const { return a + b; }
   } f;

   int n = f(1, 2);
}

可以使两个版本都引用环境变量:在本地类中,您可以添加引用成员并将其绑定在构造函数中;对于闭包,您可以将捕获列表添加到lambda表达式。

答案 2 :(得分:8)

我不知道我是否理解你,但你想要一个lambda函数?

http://en.cppreference.com/w/cpp/language/lambda

#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>


    int main()
    {
        std::vector<int> c { 1,2,3,4,5,6,7 };
        int x = 5;
        c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; } ), c.end());

        std::cout << "c: ";
        for (auto i: c) {
            std::cout << i << ' ';
        }
        std::cout << '\n';

        std::function<int (int)> func = [](int i) { return i+4; };
        std::cout << "func: " << func(6) << '\n'; 
    }

如果您没有c ++ 11x,请尝试:

http://www.boost.org/doc/libs/1_51_0/doc/html/lambda.html

答案 3 :(得分:5)

Pre C ++ 11,如果你想将函数本地化一个函数,可以这样做:

int foo () {
    struct Local {
        static int bar () {
            return 1;
        }
    };
    return Local::bar();
}

或者如果你想要更复杂的东西:

int foo (int x) {
    struct Local {
        int & x;
        Local (int & x) : x(x) {}
        int bar (int y) {
            return x * x + y;
        }
    };
    return Local(x).bar(44);
}

但是如果你想要在C ++ 11之前使用真正的函数文字,那是不可能的。

相关问题