Problems with C ++ __VA_ARGS__ macro

What are (if any) some potential problems using a C ++ macro like this? Would an inline function be a better solution?

#define EVENT_INFO(_format_, ...) CMyEvent::Generate(__FILE__, __LINE__, CMyEvent::EVT_HIGH, _format_, __VA_ARGS__)

void
CMyEvent::Generate(
    const char* file,                      // filename
    int line,                              // line number
    CMyEvent::LEVEL level,                 // severity level
    const char *format,                    // format of the msg / data
    ...)                                   // variable arguments
{
    // Get a message from the pool
    CMyEvent* p_msg = GetMessageFromPool();
    if(p_msg != NULL)
    {
        va_list arguments; // points to each unnamed argument
        va_start(arguments, format);
        // Fill the object with strings and data.
        p_msg->Fill(file, line, level, 0, format, arguments);
        va_end(arguments);
    }
}
+3
source share
3 answers

Since you use C ++, you can avoid errors when using variable argument lists, which are prone to many problems:

  • No argument count
  • Do not check argument type

To make it more C ++, do something like:

#define EVENT_INFO(args) EventLogStream (__FILE__, __LINE__, __PRETTY_FUNCTION__) << args

and call it like (warning: all code here is pseudocode and may be syntactically incorrect, but you should get the basic idea):

EVENT_INFO ("The answer to " << the_question << " is " << answer); // usually 42

An EventLogStream is similar to a cout object and, like cout, you can provide output for the class:

class Vector3D
{
   EventLogStream &operator << (EventLogStream &out) { out << "{" << x << ", " << y << ", " << z << "}"; }
}
+1

< <(), , std:: ostreams , (IMHO) , ++, C.

+1

variadic macro . , iostreams. , __FILE__, __LINE__ .

( IMHO)

0

Source: https://habr.com/ru/post/1743514/


All Articles