Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;宏解析问题_C++_Macros_C Preprocessor - Fatal编程技术网

C++ C++;宏解析问题

C++ C++;宏解析问题,c++,macros,c-preprocessor,C++,Macros,C Preprocessor,我尝试使用宏在ostringstream中本地将单个日志行排队,然后在该行结束时转储该ostringstream的全部内容。但是,我仍然希望使用流插入语法。所以我想把一条记录线变成这样: std::cerr << "Some error in my function. Code is " << errCode << " exiting" << std::endl; #define SERR(x)

我尝试使用宏在ostringstream中本地将单个日志行排队,然后在该行结束时转储该ostringstream的全部内容。但是,我仍然希望使用流插入语法。所以我想把一条记录线变成这样:

std::cerr << "Some error in my function.  Code is " << errCode << " exiting" << std::endl;
#define SERR(x)                                     \
    do {                                            \
        std::ostringstream _s;                      \
        _s << (x) << std::endl;                     \
        std::cerr << _s.str();                      \
    } while (0)

std::cerr试着展开它,看看你会得到什么:

#include <iostream>
#include <sstream>

int main()
{
    std::cout << "Hello World!\n"; 
    bool val = false;
    if (val)
        { std::ostringstream _s; ; _s << "No error" << std::endl; std::cerr << _s.str(); };
    else
        { std::ostringstream _s; ; _s << "Error" << std::endl; std::cerr << _s.str(); };
}
这不仅解决了您的问题,而且强制添加
在宏之后。否则,人们可以通过两种方式使用它:

SERR("foo")  // without ;
...
SERR("bar"); // with ;

试着扩展它,看看你能得到什么:

#include <iostream>
#include <sstream>

int main()
{
    std::cout << "Hello World!\n"; 
    bool val = false;
    if (val)
        { std::ostringstream _s; ; _s << "No error" << std::endl; std::cerr << _s.str(); };
    else
        { std::ostringstream _s; ; _s << "Error" << std::endl; std::cerr << _s.str(); };
}
这不仅解决了您的问题,而且强制添加
在宏之后。否则,人们可以通过两种方式使用它:

SERR("foo")  // without ;
...
SERR("bar"); // with ;

这就是为什么我看到这么多这样的宏(使用do-while语法)。我从来没有联系过。非常感谢。一直在编程C++,但我一直都很害怕area@Joe另外,建议像这样将参数包装在括号中
(x)
。这就是为什么我看到这么多这样的宏(使用do-while语法)。我从来没有联系过。非常感谢。一直在编程C++,但我一直都很害怕area@Joe另外,建议像这样将参数包装在括号中
(x)
。通常最好将责任分开。一般来说,将责任分开是个好主意。通用