help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Trace function


From: Ulrich Eckhardt
Subject: Re: Trace function
Date: Thu, 11 Jan 2007 07:48:12 +0100
User-agent: KNode/0.10.4

Salvatore Di Fazio wrote:
> I would like to make a function that wrote a log line in a std output.
> 
> To do this I need the name of the function that was called the Trace
> function, but I don't want put the __FUNCTION__ macro in the paramater
> of the Trace function.

You mean 'function that called the Trace function' and not 'function that
was called', right? This would twist your statement to something very
confusing. Anyhow, concerning the problem...

The typical solution for this is to create a macro that does the job, e.g.
like this:

  #define TRACE(fmt, arg) Trace( "%s: "fmt, __FUNCTION__, arg)

If you need to use a variable number of arguments, this becomes a bit more
tricky. IIRC, C99 introduces macros with a variable number of arguments,
but I'm not sure about the syntax. Otherwise, in C++, you can use a
temporary object:

 struct tracer {
   tracer( char const* file) { ... }
   void operator()( char const* fmt, ...) const { TraceV(...); }
 };
 #define TRACE tracer(__FUNCTION__)

In that case, I'd consider using a template instead of variable arguments
and only using positional placeholders (e.g. %1) instead of the then
redundant type placeholders (e.g. %d), but that part is up to you to
design.

> So exist some macro that can I use to do this?
> Something like __FUNCTION_BEFORE_IT__

FYI: those things are resolved at compile time, but a function at runtime
can be called by many other functions so this can't work without
inspecting the stack. There are tools that create a backtrace
programmatically, but I don't think you want that. Macros are generally
evil, but this case is one where I would use them nonetheless.

Uli

-- 
http://gcc.gnu.org/faq.html
http://parashift.com/c++-faq-lite/



reply via email to

[Prev in Thread] Current Thread [Next in Thread]