将宏转换为函数,但无法使用 std::stringstream 连接输入

问题描述 投票:0回答:1

我目前有一个宏:

#define MY_MACRO(cond, msg)                    \
    do                                         \
        {                                      \
            if (!(cond))                       \
            {                                  \
                std::cout << msg << std::endl; \
                std::abort();                  \
            }                                  \
    } while(0)

它用于检查布尔条件并在失败时输出一条消息。

基本用法如下:

int p = 7;
MY_MACRO(false, "test (" << p << ")");

我想用这样的函数替换它:

static inline void MY_MACRO(const bool cond, const std::stringstream& ss)
{
    if(cond == false)
    {
        std::cout << ss.str() << std::endl;
        std::abort();
    }
}

但是,

std::stringstream
似乎没有复制以前的行为,因为我在传入第二个参数时遇到编译器错误:

<source>:39:30: error: invalid operands to binary expression ('const char[7]' and 'int')
   39 |     MY_MACRO(false, "test (" << p << ")");
      |                     ~~~~~~~~ ^  ~

有没有简单的方法可以实现这一点?

c++ macros
1个回答
0
投票

好吧,基于我们简短聊天的简短 POC 如下:

#include <iostream>

#define STRINGIFY(text) #text
#define TO_STRING(text) STRINGIFY(text)

#define MY_MACRO(cond, msg)                    \
    do                                         \
        {                                      \
            if (!(cond))                       \
            {                                  \
                std::cout << msg << std::endl; \
                WhatsAppMsg(TO_STRING(msg));  \
            }                                  \
    } while(0)

    static void WhatsAppMsg(const std::string str)
    {
        std::cout << str << std::endl;
    }

    int main()
    {
        int p = 7;
        MY_MACRO(false, "test (" << p << ")");

        return 0;
    }

输出是这样的:

ASM 生成编译器返回:0 执行构建编译器返回:0 返回的程序:0 测试 (7) “测试(”<< p << ")"

只需记住清理字符串化的引号,现在应该更容易,因为它是标准字符串。

© www.soinside.com 2019 - 2024. All rights reserved.