Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure that every method of a class calls some other method first?

Tags:

c++

c++11

I have :

class Foo {    public:       void log() { }        void a() {          log();       }        void b() {          log();       } }; 

Is there a way that I can have each method of Foo, call log(), but without me having to explicitly type log() as the first line of each function ? I want to do this, so that I can add behaviour to each function without having to go through each function and make sure the call is made, and also so that when I add new functions, the code is automatically added...

Is this even possible ? I can't imagine how to do this with macro's, so not sure where to begin... The only way I have thought of so far, is to add a "pre-build step", so that before compiling I scan the file and edit the source code, but that doesn't seem very intelligent....

EDIT: Just to clarify - I don't want log() to call itself obviously. It doesn't need to be part of the class.

EDIT: I would prefer using methods that would work cross platform, and using only the stl.

like image 679
Rahul Iyer Avatar asked Feb 03 '17 08:02

Rahul Iyer


People also ask

What is a method that calls another method?

Recursion is a method that call itself. In this case it is a recursion.

How do you call a method from another method in the same class?

In this program, you have to first make a class name 'CallingMethodsInSameClass' inside which you call the main() method. This main() method is further calling the Method1() and Method2(). Now you can call this as a method definition which is performing a call to another lists of method.

Can you call methods within methods?

Java does not support “directly” nested methods. Many functional programming languages support method within method. But you can achieve nested method functionality in Java 7 or older version by define local classes, class within method so this does compile.

Can you call methods from a different class?

Calling a private method from another ClassA private method can be called from another Class by using reflection API. A private method has more accessibility restrictions than other methods. A private method can be accessed from another class using getDeclaredMethod(), setAccessible() and invoke() methods of the java.


1 Answers

Thanks to the unusual properties of operator ->, we can inject code before any member access, at the expense of a slightly bent syntax:

// Nothing special in Foo struct Foo {     void a() { }     void b() { }     void c() { } };  struct LoggingFoo : private Foo {     void log() const { }      // Here comes the trick     Foo const *operator -> () const { log(); return this; }     Foo       *operator -> ()       { log(); return this; } }; 

Usage looks as follows:

LoggingFoo f; f->a(); 

See it live on Coliru

like image 173
Quentin Avatar answered Sep 19 '22 21:09

Quentin