Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 690
Ivan G. Avatar asked Apr 19 '11 15:04

Ivan G.


People also ask

What is a proxy class?

A proxy class implements exactly the interfaces specified at its creation, in the same order. If a proxy class implements a non-public interface, then it will be defined in the same package as that interface. Otherwise, the package of a proxy class is also unspecified.

What is a proxy class C++?

A proxy class in C++ is used to implement the Proxy Pattern in which an object is an interface or a mediator for some other object. A typical use of a proxy class in C++ is implementing the [] operator since the [] operator may be used to get data or to set data within an object.

What is a proxy in programming?

A proxy server is a dedicated computer or a software system running on a computer that acts as an intermediary between an endpoint device, such as a computer, and another server from which a user or client is requesting a service.

What is proxy in OOP?

Proxy is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.


2 Answers

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.

like image 151
Lou Franco Avatar answered Oct 23 '22 11:10

Lou Franco


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

like image 1
Tomek Avatar answered Oct 23 '22 10:10

Tomek