'Execute method on expression end in C++?
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?
Solution 1:[1]
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 the auto& a hard requirement?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MSalters |
