在 C++ 中的表达式末尾执行方法?
我正在设计一个自定义任务管理系统。为此,我重载了 + 和 - 运算符,以便它们获得另一种含义:
const auto& scope = fsm::enter +STATE_TO_SET -LOCK_TO_ACQUIRE;
您可以想象 STATE_TO_SET 和 LOCK_TO_ACQUIRE 都是枚举值,它们被一个接一个地“添加”到对象成员变量中。现在,fsm::enter
对象中应该有一个方法,一旦所有 + 和 - 操作完成(例如设置状态并获取锁),该方法就会触发。这在 C++11 中是否可行?
I'm designing a custom task management system. For this I'm overloading the + and - operators so they gain an alternative meaning:
const auto& scope = fsm::enter +STATE_TO_SET -LOCK_TO_ACQUIRE;
You can imagine that STATE_TO_SET and LOCK_TO_ACQUIRE are both enum values which are "added" to the objects member variables one after another. Now, there should be a method in the fsm::enter
-object that triggers once all + and - operations are done (e.g. to set the state and acquire the lock). Is this doable somehow in C++11?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
几乎 - 这是一个众所周知的解决方案。
operator+
返回一个包装对象。由于这是临时的,因此它会在完整表达式结束时被销毁。因此,它的析构函数可以运行您想要的代码。“几乎”是因为您使用了
auto&
。这将推导出临时类型,然后拒绝绑定非常量引用。auto&
是硬性要求吗?Almost - this is a well-known solution. The
operator+
returns a wrapper object. Since this is a temporary, it's destroyed at the end of the full expression. And for that reason, its destructor can run the code you want.The "almost" is because you use
auto&
. That will deduce the temporary type, and then refuse to bind a non-const reference. Is theauto&
a hard requirement?