本文介绍了编写一个宏来字符串化结构的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个宏来扩展结构的内容:

I am trying to write a macro to expand the contents of a struct:

struct Str
{
    int a;
    float f;
    char *c;
};
Str s = {123, 456.789f, "AString"};

#define STRINGIFY_STR(x) ... // Macro to stringify x which is an instance of Str

printf("%s", STRINGIFY_STR(s));

所需的输出:[a: 123, f:456.789, c:AString]

desired output: [a: 123, f:456.789, c:AString]

是否可以编写一个宏来执行此操作?如果是,那怎么办?

Is it possible to write a macro that does this? If it is, then how?

推荐答案

你有什么理由想用宏来做这个吗?

Is there a reason you want to do this as a macro?

您应该编写一个函数来执行此操作,而不是使用预处理器.

You should write a function to perform this action instead of using the preprocessor.

根据您的目标,有几种选择.boost 格式化库 提供了一个很好的工具包来构建格式化字符串.您总是可以重载operator<< 也提供干净的输出.

Depending on your goals, there are a few options. The boost formatting library provides a great toolkit to build the formatted string. You could always overload operator<< to provide clean output, as well.

如果您使用纯 C 语言执行此操作,sprintf 系列用于创建格式化输出的方法.

If you're doing this in pure C, the sprintf family of methods work for creating formatted output.

这篇关于编写一个宏来字符串化结构的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 20:41