Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile time RAII type of behavior using C++

Tags:

c++

templates

I know it sounds a bit wierd but this is what I want to do: Lets say I have a function void f() and I want to add tracing for this method. I want to trace the enrty of this function and the exit of the function by having trace messages such as "Entered function f" and "Exited function f". I don't want to add manual trace entries for the entry and exit as I might missout on some of return paths. So is possible to use the template magic at compile time and have these strings automatically generated. i.e. what I want to achieve is

void f()
{
  some_template<magic>("f");
}

This should add a trace message "Entered function f" in constructor and "Exited function f" in destructor. I want it compile time and don't want to create any runtime objects. Is it possible in C++? any pointers where I can find more info if this can be achieved?

like image 593
Asha Avatar asked Feb 24 '23 01:02

Asha


1 Answers

The point at which the method is left is only known at runtime, since any kind of exception can happen at any point in your code (generally speaking). Hence, no compile-time solution is possible here.

like image 114
Björn Pollex Avatar answered Mar 07 '23 03:03

Björn Pollex