0%

Simulate javascript's closure in C++

好久沒寫些東西了,雖然這篇沒什麼實用價值。在C++這種語言要模擬FP的Closure是做得到,不過不好用
這邊的Clouse跟C++的Lambda Closure不太相同。
先看正常版的C++ Code

1
2
3
4
5
6
struct Counter {
int value = 0;
void inc() { value++; }
};
Counter c;
c.inc();

一目了然的程式,也不用解釋太多。
模擬版的FP Closure

1
2
3
4
5
6
7
8
9
10
11
12
struct Counter {
int value = 0;
};
std::function<void(void)> make_inc()
{
std::shared_ptr<Counter> obj = make_shared<Counter>();
return [obj]() {
obj->value++;
};
}
std::function<void(void)> inc = make_inc();
inc();

真是囉唆。 Javascript還可以輸出多個函數。如果要用C++也能作到,像這樣

1
2
3
4
5
6
7
8
9
10
11
12
typedef std::function<void(void)> Func;
std::tuple<Func, Func> make_counter()
{
std::shared_ptr<Counter> obj = make_shared<Counter>();
Func inc = [obj]() { obj->value++; };
Func dec = [obj]() { obj->value--; };
return make_tuple(inc, dec);
}
auto funcs = make_counter();
Func inc = std::get<0>(funcs);
Func dec = std::get<1>(funcs);
inc();

tuple和get來抓取函數時再不怎麼漂亮,也許C++17的Structured bindings可以改善這個問題。

Reference

Returning multiple values from functions in C++
Emulating C++17 Structured Bindings in C++14