How do I change the expansion order of arguments to macro functions?

I have the following code:

#include <iostream>
#include <stdexcept>

#define TRACE_MACRO(EnterText) \
class CTrace \
{ \
public: \
CTrace() \
{ \
std::cout << EnterText;  \
} \
private:\
};

#define DO_TRACE TRACE_MACRO("[ENTER] " __FUNCTION__ "\r\n") CTrace trace

static void test()
{
    DO_TRACE;
}

int main(int, char**)
{
    DO_TRACE;
    test();
    return 0;
}

      

What are the outputs:

[ENTER] main::CTrace::CTrace
[ENTER] test::CTrace::CTrace

      

How to write a macro such that it __FUNCTION__

expands first so that the output is as follows:

[ENTER] main
[ENTER] test

      

I tried to create a helper macro called DO_TRACE2 that forwards arguments, but that leads to the same output.

If this is not possible, then what about a macro that will compile time, adjust the text to remove the CTrace :: CTrace part of the line?

Edit: Please note that I don't want to pass a compile-time string pointer for this class, I want the std :: cout call to render as if I had manually written std :: cout <<<<<<<<<< <<; "Main";

+3


source to share


2 answers


Untested, but here's a simple permutation that might work:



#define TRACE_MACRO \
class CTrace \
{ \
public: \
CTrace(const char* text) \
{ \
std::cout << text;  \
} \
private:\
};

#define DO_TRACE TRACE_MACRO CTrace trace("[ENTER] " __FUNCTION__ "\r\n")

      

+3


source


Jimmy asked

need to define a whole new class in def macro?

And you answered:

@Jimmy no, I just need a call to std :: cout to use compile-time const static strings, not a compile-time pointer to the string, if that makes sense.

So why not just drop the class:

#define DO_TRACE std::cout << "[ENTER] " << __FUNCTION__ << "\r\n"

      

This will output:



[ENTER] main 
[ENTER] test

      

and uses the static compile time const string ...

I probably missed something, just tell me I'll delete this post ....

BTW, I compiled the code from your post using GNU GCC version 4.8.1 from http://www.compileonline.com/compile_cpp_online.php . It outputs

[ENTER] CTrace 
[ENTER] CTrace

      

This is how the FUNCTION macro is resolved in different ways by compilers ...

+1


source







All Articles