How can I abstract out a repeating try catch pattern in C++

前端 未结 7 1173
眼角桃花
眼角桃花 2020-12-15 04:28

I have a pattern that repeats for several member functions that looks like this:

int myClass::abstract_one(int sig1)
{
  try {
    return _original->abstr         


        
7条回答
  •  执笔经年
    2020-12-15 05:21

    Use boost::function and boost::bind. Works with any function signature so long as the return type matches;

    #include 
    #include 
    
    using boost::function;
    using boost::bind;
    
    template
    T exception_wrapper(boost::function func)
    {
      try {
        return func();
      } catch (std::exception& err) {
        handleException(err);
      } catch (...) {
        handleException();
      }
    }
    
    // ways to call
    int result = exception_wrapper(bind(libraryFunc, firstParam));
    // or a member function
    LibraryClass* object;
    result = exception_wrapper(bind(&LibraryClass::Function, object, firstParam));
    
    // So your wrapping class:
    class YourWrapper : public SomeInterface
    {
    public:
        int abstract_one(int sig1)
        {
            return exception_wrapper(bind(&LibraryClass::concrete_one, m_pObject, sig1));
        }
    
        bool abstract_two(int sig1, int sig2)
        {
            return exception_wrapper(bind(&LibraryClass::concrete_two, m_pObject, sig1, sig2));
        }
    
        // ...
    
    private:
       LibraryClass* m_pObject;
    };
    

提交回复
热议问题