开发者

C++ proxy class

Is there any way to easily implement a proxy class pattern in C++? Not using AspectC++ or other heavy tools, 开发者_JAVA技巧just built-in macro or templates.

Explaining what I want:

class base_class
{
  public:
   virtual void method_one() { ... }
   virtual void method_two() { ... }
}

class class_proxy : base_class
{
   protected:
    void before_any_method_call() { do stuff };
    void after_any_method_call(std::exception* ex) { do stuff }
}

Here is the scenario. A class I want to proxy (base_class) does remote calls, however when a network is down it will throw a transport exception derived from std::exception. base_class has tons of method, and I'd like to catch the transport exception, respond with an empty result, and reestablish connection before the next method call.


If you mean something that is auto-generated via something like reflection, no. One common way to implement simple proxies is to override the operator-> of the proxy class. This works if whatever you need to do in the proxy can be done at that time. This technique is in "Design Patterns" by the GoF, under the Implementation section.

Edit (based on your additional info): If you want to do something before every call, the operator->() overload mechanism works well for this. To do something after every call is not as easy to automate, but I could imagine something being built out of a special return object that calls it when it destructs.


This may help http://www.stroustrup.com/wrapper.pdf‎, however I don't think it is possible to handle exceptions this way.


I am not sure derivation is the best design for proxy pattern. Your post is perhaps out of date but I have a sample version of Proxy Pattern to secure array and STL containers element access here. It uses template programming and the last C++17 features : the deduction guides!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜