在C++中通常用某种前缀命名成员变量来表示它们是成员变量而不是局部变量或参数.如果你来自MFC背景,你可能会使用m_foo.我myFoo偶尔也见过.
C#(或者可能只是.NET)似乎建议只使用下划线,如_foo.这是否允许C++标准?
例:
#define FOO(...) printf(__VA_ARGS__)
#define BAR(fmt, ...) printf(fmt, __VA_ARGS__)
FOO("this works fine");
BAR("this breaks!");
Run Code Online (Sandbox Code Playgroud)
BAR()根据C99标准,上述用途确实不正确,因为它将扩展到:
printf("this breaks!",);
Run Code Online (Sandbox Code Playgroud)
请注意尾随逗号 - 不可行.
一些编译器(例如:Visual Studio 2010)将悄然摆脱那个尾随的逗号.其他编译器(例如:GCC)支持放在##前面__VA_ARGS__,如下所示:
#define BAR(fmt, ...) printf(fmt, ##__VA_ARGS__)
Run Code Online (Sandbox Code Playgroud)
但有没有符合标准的方法来获得这种行为?也许使用多个宏?
现在,该##版本似乎得到了相当好的支持(至少在我的平台上),但我真的更喜欢使用符合标准的解决方案.
先发制人:我知道我可以写一个小功能.我正在尝试使用宏来做到这一点.
编辑:以下是我想要使用BAR()的一个例子(虽然简单):
#define BAR(fmt, ...) printf(fmt "\n", ##__VA_ARGS__)
BAR("here is a log message");
BAR("here is a log message with a param: %d", 42);
Run Code Online (Sandbox Code Playgroud)
这会自动为我的BAR()日志记录语句添加换行符,假设fmt它始终是双引号C字符串.它不会将换行符打印为单独的printf(),如果日志记录是行缓冲的并且异步来自多个源,则这是有利的.
00001 /* assert.h
00002 Copyright (C) 2001, 2003 Free Software Foundation, Inc.
00003 Written by Stephane Carrez (stcarrez@nerim.fr)
00004
00005 This file is free software; you can redistribute it and/or modify it
00006 under the terms of the GNU General Public License as published by the
00007 Free Software Foundation; either version 2, or (at your option) any
00008 later version.
00009
00010 In addition to the permissions in the GNU General Public License, the
00011 Free Software Foundation gives …Run Code Online (Sandbox Code Playgroud) #include <stdio.h>
#define foo(x, y) #x #y
int main()
{
printf("%s\n", foo(k, l));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
kl
我知道##会连接.从输出看来,它似乎#也是连接.我对么?
如果我是正确的那么##运营商和#运营商之间有什么区别?