目前,我使用下面的函数模板以抑制未使用的变量的警告:

template<typename T>
void
unused(T const &) {
  /* Do nothing. */
}

然而,移植从Linux到在cygwin的时候,我正在根据G ++ 3.4.4编译器错误(在Linux上我是3.4.6,所以也许这是一个bug修复?):

Write.cpp: In member function `void* Write::initReadWrite()':
Write.cpp:516: error: invalid initialization of reference of type 'const volatile bool&' from expression of type 'volatile bool'
../../src/common/Assert.h:27: error: in passing argument 1 of `void unused(const T&) [with T = volatile bool]'
make[1]: *** [ARCH.cygwin/release/Write.o] Error 1

要的未使用的参数是一个成员变量声明为:

  volatile bool readWriteActivated;

这是一个编译器缺陷或在我的代码中的错误?

下面是最小测试用例:

template<typename T>
void unused(T const &) { }

int main() {
  volatile bool x = false;
  unused(!x); // type of "!x" is bool
}
有帮助吗?

解决方案 3

有编译器故障并且不存在已知的变通:

http://gcc.gnu.org/bugzilla/show_bug.cgi ?ID = 42655

有被固定在V4.4。

其他提示

说明你不实际使用参数的实际方法是不是给它一个名称:

int f(int a, float) {
     return a*2;
}

将编译处处与所有警告导通时,没有警告关于未使用的浮子。即使该参数并在原型有一个名称(例如int f(int a, float f);),它仍然不会抱怨。

我不是100%肯定这是便携式的,但是这是我平时用来抑制对未使用的变量警告成语。这里的背景是一个信号处理程序,只用来捕捉SIGINTSIGTERM,所以如果函数永远叫我知道它的时候,程序退出。

volatile bool app_killed = false;
int signal_handler(int signum)
{
    (void)signum; // this suppresses the warnings
    app_killed = true;
}

我倾向于不喜欢弄乱与__attribute__((unused))参数列表中,由于铸到空隙特技工作不诉诸宏视觉C ++。

在GCC,可以按如下方式定义一个宏:

#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*@unused@*/ x
#else
# define UNUSED(x) x
#endif 

标有此宏的任何参数将抑制未使用的警告GCC发射(和重命名参数与UNUSED_的前缀)。对于Visual Studio,您可以抑制警告与#pragma指令。

通过haavee(由UR修正)所提出的答案是一个我通常会使用:

int f(int a, float /*epsilon*/) {
     return a*2;
}

当参数是有时但不总是在该方法中使用,e.g真正的问题发生:

int f(int a, float epsilon) {
#ifdef LOGGING_ENABLED
     LOG("f: a = %d, epsilon = %f\n", a, epsilon);
#endif
     return a*2;
}

现在,我不能评论了参数名小量,因为这会打破我的记录版本(我不想插入其它的#ifdef参数列表,因为这会使代码更难读)。

所以,我认为最好的办法是使用汤姆的建议:

int f(int a, float epsilon) {
(void) epsilon;    // suppress compiler warning for possibly unused arg
#ifdef LOGGING_ENABLED
     LOG("f: a = %d, epsilon = %f\n", a, epsilon);
#endif
     return a*2;
}

我唯一担心的是,一些编译器会发出警告的“(无效)小量;”声明中,例如“声明没有效果”警告或一些这样的 - 我想我就来测试一下所有我可能使用的编译器...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top