Nat*_*man 22 c++ printf gcc string-formatting
我正在尝试为调试打印定义一个类方法,其行为类似于printf
:
inline void debug(const char* fmt, ...) __attribute__ ((format (printf, 1, 2)))
Run Code Online (Sandbox Code Playgroud)
这抱怨:
error: format string argument not a string type
Run Code Online (Sandbox Code Playgroud)
我记得类方法声明有一个隐式this
参数,所以我将参数的位置更改为2,3:
inline void debug(const char* fmt, ...) __attribute__ ((format (printf, 2, 3)))
Run Code Online (Sandbox Code Playgroud)
现在它编译,但看起来像参数被移位,就好像this
参数被视为参数列表的一部分.
如何判断this
不属于我要打印的字符串的函数?
Chr*_*odd 22
你做到了. this
是参数1,所以通过说format(printf, 2, 3)
你告诉编译器你不打印this
,你打印参数2(fmt
)以及其他参数.
将静态成员与非成员同等对待。讨论给了我答案,但其他人值得注意:
我发现这一点是因为我们有一些进程使用这样的日志助手,并且四分之一的进程需要__attribute__ (( format( printf, 2, 3 ) ))
与其他三个进程配合使用__attribute__ (( format(printf, 1, 2) ))
- 事实证明它是非静态的......
@克里斯·多德是正确的。这是支持它的最新 gcc 文档(感谢Foxit reader让我在 Linux 上标记 PDF)。特别注意下图中绿色标记的部分。
由于非静态 C++ 方法具有隐式 this 参数,因此在为和提供值时,此类方法的参数应从2开始计数,而不是从 1 开始。
string-index
first-to-check
来源: https: //gcc.gnu.org/onlinedocs/gcc-8.2.0/gcc/Common-Function-Attributes.html#Common-Function-Attributes(请参阅标题为“格式(原型、字符串索引、第一个-去检查)”)。
图像(尤其是绿色突出显示):