I was watching a video called Lambda? You Keep Using that Letter by Kevlin Henney, where he states that closures and objects are fundamentaly equivalent:
He then proves his point by this javascript code which implement a stack as a closure:
const newStack = () => {
const items = []
return {
depth: () => items.lengh,
top: () => items[0],
push: newTop => { items.unshift(newTop) },
pop: () => { items.shift() },
}
}
The advantage of a closure versus a class is that its state is really hidden, whereas a private member is more "inaccessible" than "hidden".
I tried to do something equivalent in C++. However, it seems that it is difficult to express this in C++.
My current version is there, and it has two major drawbacks:
it does compile, but it will not work (the inner
shared_ptris released immediately after the closure creation)is a bit verbose : depth, top, push and pop are repeated 3 times.
auto newStack = []() {
auto items = std::make_shared<std::stack<int>>();
auto depth = [&items]() { return items->size();};
auto top = [&items]() { return items->top(); };
auto push = [&items](int newTop) { items->push(newTop); };
auto pop = [&items]() { items->pop(); };
struct R {
decltype(depth) depth;
decltype(top) top;
decltype(push) push;
decltype(pop) pop;
};
return R{ depth, top, push, pop};
};
Is there a working way to do it in C++?