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

前端 未结 7 1170
眼角桃花
眼角桃花 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:25

    My answer is conceptually similar to James McNellis', except that I use boost::bind to do the heavy lifting:

    using boost::bind;
    
    class myClass
    {
    public:
      myClass(origClass * orig) : orig_(orig) {}
    
      int f1(bool b) { return wrapper(bind(&origClass::f1, orig_, b)); }
      bool f2(int i) { return wrapper(bind(&origClass::f2, orig_, i)); }
      void f3(int i) { return wrapper(bind(&origClass::f3, orig_, i)); }
    private:
      origClass * orig_;
    
      template <typename T> 
      typename T::result_type wrapper(T func)
      {
        try {
          return func();
        } 
        catch (std::exception const &e) {
          handleError(e);
        }
        catch (...) {
          handleError();
        }
      }
    };
    

    Note that I wouldn't use a boost::function here as it can interfere with inlining.

    0 讨论(0)
提交回复
热议问题