简单实现了一下,还是能用的。
#include <iostream>
#include <functional>
#include <exception>
#include <memory>
class Finally {
public:
template <typename F>
Finally(F f) : cleanup(f) {}
~Finally() {
if (cleanup) cleanup();
}
private:
std::function<void()> cleanup;
};
template<typename TryBlock, typename CatchBlock, typename FinallyBlock>
void TryCatchFinally(TryBlock tryBlock, CatchBlock catchBlock, FinallyBlock finallyBlock) {
auto finallyGuard = Finally([&](){ finallyBlock(); });
try {
tryBlock();
} catch (std::exception& e) {
catchBlock(e);
}
}
int main() {
TryCatchFinally(
[]() {
std::cout << "Try block executed." << std::endl;
// throw std::runtime_error("Test exception");
},
[](std::exception& e) {
std::cout << "Catch block executed." << std::endl;
std::cout << e.what() << std::endl;
},
[]() {
std::cout << "Finally block executed." << std::endl;
}
);
return 0;
}