[英]How do define anonymous functions in C++?
我可以在 C++ 中內聯定義函數嗎? 我不是在談論 lambda 函數,也不是導致編譯器優化的inline
關鍵字。
C++11 向語言添加了lambda 函數。 該語言的先前版本(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;
});
在 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 表達式添加捕獲列表。
我不知道我是否理解你,但你想要一個 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,請嘗試:
在 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 之前的真正函數字面量,那是不可能的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.