您最常用的C宏用于打印不同类型的变量值 [英] Your most general C macro for printing variable values in different types

查看:133
本文介绍了您最常用的C宏用于打印不同类型的变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请与我们分享您最喜欢的,最普通的PRINT或DEBUG宏
适用于所有(或几乎所有)不同类型的变量和C中的数组。宏
可以有任何数字的参数(优选1-3);如果增加
描述功能,可以假设C99功能。

Please share with us your favorite, and most general, PRINT or DEBUG macro applicable to all (or almost all) variables in different types and to arrays in C. The macro can have any number of parameters (though 1-3 are preferred); if it increases descriptive power at all, C99 features can be assumed.

#define PRINT(var, ...) \
   ...

让我们开始吧

推荐答案

对于C ++,模板函数可以比宏强得多。

For C++, template function can be much more powerful than macro.

template <typename T>
std::string tostring(const T& t);

模板参数的缺点是它无法区分typedef别名:

The drawback of template argument is that it cannot distinguish between typedef aliases:

typedef LONG HRESULT;

对于C,我认为没有什么可以做,而不改变你的结构。如果您有对struct定义的控制,这里有两个技巧:

For C, I think there is nothing you can do, without changing your structs. If you have control over the struct definitions, here are two tricks:

将一个字段添加到结构的开头,并将该字段设置为唯一标识可以由 tostring 函数使用的结构类型来选择适当的打印代码。

Add a field to the beginning of the struct, and set the field to a value that uniquely identifies the type of the structure, which can be used by the tostring function to choose the appropriate printing code.

typedef struct abcde
{
    int unique_struct_type_id; // assign this to a number that represents "abcde"
};

类似的方法是传递一个用于打印结构体的函数指针。

A similar method is to pass in a function pointer for printing the struct.

struct abcde
{
    void (*print_fn) (abcde* p);  // assign this to the printing function for "abcde"
}
#define PRINT_STRUCT(s) s->print_fn(s)

这篇关于您最常用的C宏用于打印不同类型的变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆