|
|
|
|
|
by vidarh
4637 days ago
|
|
I haven't written much C++ in quite a few years - mostly do Ruby these days, so I'm sure I'm making some terribly embarrassing faux pas or other with the example below. But you don't need more than the C++ functionality to compose your own variations if you want more flexibility. For example: #include <vector>
#include <iostream>
class Scope {
private:
typedef std::vector<void (*)()> FV;
FV fv;
public:
void on_return(void (* f)()) {
fv.push_back(f);
}
~Scope() {
for (FV::iterator it = fv.begin(); it != fv.end(); ++it) {
(*it)();
}
}
};
void foo() {
std::cout << "Hello ";
}
void bar() {
std::cout << "World" << std::endl;
}
int main() {
Scope scope;
scope.on_return(foo);
scope.on_return(bar);
std::cout << "Hi" << std::endl;
}
With C++11 lambda syntax you can do quite a bit better.Expanding that into something providing at least most of what Go's "defer" does shouldn't be too hard. |
|
It also optimizes nicely, which yours may not because the loop unrolling may be complicated and there's a higher chance of aliasing of the function pointers in the vector: