Domanda

First of all, let me say that I'm not a guru C++ programmer. I have a few years of experience in C++, but my main area is .NET/C#.

I'm looking into a way to create dynamic proxy/wrapper classes in C++. Particularly, what I want to achieve is to intercept a method call. This kind of tricks is common in Java/.NET world, but C++ lacks Reflection.

I found an online tutorial, which explains how to create a wrapper and intercept method calls through -> operator overloading:

class Person{
  std::string mName;
  Person(std::string pName): mName(name){}
  void printName(){
     std::cout << mName << std::endl;
  }

};

template <class T >
class Wrap {
     T * p ;
     public:
             Wrap (T * pp ) :p (pp) { }
             Call_proxy <T> operator ->() {
                   prefix ();
                   return Call_proxy<T>(p);
             }
};
template <class T >
class Call_proxy {
       T * p ;
       public :
              Call_proxy (T * pp ) :p (pp ){ }
              ˜Call_proxy () {
                     suffix ();
               }
               T * operator ->() {
                          return p ;
                }
 };

As you can see from this sample, we can catch method calls events, before and after call, but what is not clear for me, is how to detect which method is being called? Is it possible at all?

Thanks

UPDATE

Allright, to make things more clear, I don't really care if the implementation would be truly dynamic or not. Having a wrapper class similar to smart pointers is fine for me.

È stato utile?

Soluzione

No. This is designed specifically to be non intrusive, All the wrappers do is facilitate the calling of prefix and suffix and then return the object that is being referenced so that it can call the specified function. If the -> operator is overloaded then, object->function() gets expanded to object.operator->()->function().

Here is a link to the paper Stroustrup wrote, it's very informative http://www.stroustrup.com/wrapper.pdf

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top