[C++] 一个不是很完美的try-cache-finally

简单实现了一下,还是能用的。

#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;
}
1 个赞

改进建议:cache也应该支持自定义类型才可以,并且能自定义cache的种类个数