项目作者: BlackMATov

项目描述 :
Go's defer implementation in C++17
高级语言: C++
项目地址: git://github.com/BlackMATov/defer.hpp.git
创建时间: 2020-06-04T16:07:32Z
项目社区:https://github.com/BlackMATov/defer.hpp

开源协议:MIT License

下载


defer.hpp

Go’s defer implementation in C++17

linux
darwin
windows
language
license

Requirements

Installation

defer.hpp is a header-only library. All you need to do is copy the headers files from headers directory into your project and include them:

  1. #include "defer.hpp/defer.hpp"

Also, you can add the root repository directory to your cmake project:

  1. add_subdirectory(external/defer.hpp)
  2. target_link_libraries(your_project_target PUBLIC defer.hpp::defer.hpp)

Examples

Basic Defer

  1. if ( FILE *file = std::fopen("output.txt", "a") ) {
  2. // defer will close the file after scope or on exception
  3. DEFER_HPP([file]{ std::fclose(file); });
  4. const char buffer[] = "hello world\n";
  5. if ( 12 != std::fwrite(buffer, sizeof(buffer[0]), std::strlen(buffer), file) ) {
  6. throw std::runtime_error("some exception");
  7. }
  8. }

Error Defer

  1. if ( FILE *file = std::fopen("output.txt", "a") ) {
  2. // defer will close the file after scope or on exception
  3. DEFER_HPP([file]{ std::fclose(file); });
  4. // error defer will be called on exception
  5. ERROR_DEFER_HPP([]{
  6. std::cerr << "there is something wrong" << std::endl;
  7. });
  8. const char buffer[] = "hello world\n";
  9. if ( 12 != std::fwrite(buffer, sizeof(buffer[0]), std::strlen(buffer), file) ) {
  10. throw std::runtime_error("some exception");
  11. }
  12. }

Return Defer

  1. if ( FILE *file = std::fopen("output.txt", "a") ) {
  2. // defer will close the file after scope or on exception
  3. DEFER_HPP([file]{ std::fclose(file); });
  4. // return defer will be called on successful scope exit
  5. RETURN_DEFER_HPP([]{
  6. std::cout << "all is ok!" << std::endl;
  7. });
  8. const char buffer[] = "hello world\n";
  9. if ( 12 != std::fwrite(buffer, sizeof(buffer[0]), std::strlen(buffer), file) ) {
  10. throw std::runtime_error("some exception");
  11. }
  12. }

License (MIT)