【发布时间】:2020-09-01 20:28:49
【问题描述】:
我正在观看 Kevlin Henney 的名为 Lambda? You Keep Using that Letter 的视频,他在视频中指出闭包和对象在根本上是等价的:
然后他通过this javascript code 证明了他的观点,this javascript code 将堆栈实现为闭包:
const newStack = () => {
const items = []
return {
depth: () => items.lengh,
top: () => items[0],
push: newTop => { items.unshift(newTop) },
pop: () => { items.shift() },
}
}
闭包相对于类的优势在于它的状态实际上是隐藏的,而私有成员比“隐藏”更“不可访问”。
我尝试在 C++ 中做一些等效的事情。但是,这似乎很难用 C++ 来表达。
我目前的版本在那里,它有两个主要缺点:
它可以编译,但它不起作用(内部
shared_ptr在闭包创建后立即释放)有点冗长:depth、top、push 和 pop 重复了 3 次。
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};
};
在 C++ 中有一种可行的方法吗?
【问题讨论】:
-
您的程序可以编译,但实际上并不能运行并打印出正确的结果。
-
@cigien 你是对的。我需要对此进行调查
-
@cigien:我更新了问题是为了说明代码实际上是错误的