C++ proxy class
Is there any way to easily implement a proxy class pattern in C++? Not using AspectC++ or other heavy tools, 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.
这可能有助于http://www.stroustrup.com/wrapper.pdf,但我不认为有可能以这种方式处理异常。
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!
链接地址: http://www.djcxy.com/p/52082.html下一篇: C ++代理类