這樣的關閉實現有沒有問題(從python黑客竊取)?C++關閉破解
void function(int value) {
struct closure {
closure(int v = value) : value_(value) {}
private: int value_;
};
closure c;
}
經過進一步調查,出現在成員函數中,局部變量不能用作默認值,但是對象變量可以。
這樣的關閉實現有沒有問題(從python黑客竊取)?C++關閉破解
void function(int value) {
struct closure {
closure(int v = value) : value_(value) {}
private: int value_;
};
closure c;
}
經過進一步調查,出現在成員函數中,局部變量不能用作默認值,但是對象變量可以。
這看起來是一個關閉的好基礎。更多的是一種成語,而不是黑客,因爲你正在使用語言功能來達到他們的預期目的。
當然,你的例子沒有做任何事情。它只能在function
之內使用。
無端的C++ 0x插頭:
#include <functional>
void some_function(int x) { }
void function(int value) {
struct closure {
std::function< void() > operator()(int value)
{ return [=](){ some_function(value); }; }
};
auto a = closure()(value);
auto b = closure()(5);
a();
b();
b();
}
封閉的C++當量:
class Closure
{
public:
Closure(std::string const& g)
:greet(g)
{}
void operator()(std::string const& g2)
{
std::cout << greet << " " << g2;
}
private:
std::string greet;
};
int main()
{
Closure c("Hello");
c("World"); // C acts like a function with state. Whooo.
}
隨着C++ 11新lambda語法變得更容易。
int main()
{
std::string g("Hello");
auto c = [g](std::string const& m) {std::cout << g << " " << m;};
c("World");
}
使用C++ 14中的新擴展lambda語法(gcc上的-std = C++ 1y),它變得更加容易。
int main()
{
auto c = [g="Hello"](std::string const& m) {std::cout << g << " " << m;};
c("World");
}
偉大的易於得到的例子,(+) – Wolf 2014-09-25 10:27:46
@Wolf:用C++ 11更新 – 2014-09-25 18:41:13
這是大多數其他語言在幕後捕獲具有本地函數的局部變量時所做的。例如,使用匿名代理和捕獲的變量反編譯C#代碼。 – 2010-09-01 00:25:51
您需要明確地將值傳遞給構造函數:函數的默認參數不能是局部變量。該規則適用於_all_函數,而不僅僅是成員函數。 – 2010-09-01 00:35:17
@詹姆斯,謝謝我不知道規則很好 – Anycorn 2010-09-01 00:37:33