相关疑难解决方法(0)

在C++标识符中使用下划线有哪些规则?

在C++中通常用某种前缀命名成员变量来表示它们是成员变量而不是局部变量或参数.如果你来自MFC背景,你可能会使用m_foo.我myFoo偶尔也见过.

C#(或者可能只是.NET)似乎建议只使用下划线,如_foo.这是否允许C++标准?

c++ standards naming-conventions c++-faq

906
推荐指数
4
解决办法
24万
查看次数

GCC的标准替代## __ VA_ARGS__技巧?

C99中的可变参数宏存在一个众所周知的 空args 问题.

例:

#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(),如果日志记录是行缓冲的并且异步来自多个源,则这是有利的.

c c99 c-preprocessor variadic-macros

141
推荐指数
6
解决办法
7万
查看次数

C++断言assert.h中的实现

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)

c++ implementation assert

12
推荐指数
2
解决办法
1万
查看次数

#运算符在宏中做什么?

#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

我知道##会连接.从输出看来,它似乎#也是连接.我对么?

如果我是正确的那么##运营商和#运营商之间有什么区别?

c macros

5
推荐指数
1
解决办法
187
查看次数