修复"-Wunused-parameter"取决于预处理器条件的警告

Fixing "-Wunused-parameter" warning which depends on pre-processor conditions

本文关键字:条件 警告 处理器 预处理 -Wunused-parameter 取决于 修复      更新时间:2023-10-16

当变量的使用取决于预处理器指令(#if,#else...(条件时,如何修复"-Wunused-parameter"警告。

void foo(std::string& color)
{
#ifdef PRINT
printf("Printing color: ", color);
#endif
}

我已经看到(void(的用法,例如:

void foo(std::string& color)
{
#ifdef PRINT
printf("Printing color: ", color);
#else
(void)color;
#endif
}

这是正确的方法吗?

[ 注意 ]:这里提到的例子是我实际用例的一个非常低的例证。

我真的很喜欢使用std::ignore:

// Example program
#include <iostream>
#include <string>
#include <tuple> // for std::ignore
void foo(std::string& color)
{
#ifdef PRINT
printf("Printing color: ", color.c_str());
#else
std::ignore = color;
printf("Not printing any color");
#endif
}

现在,老实说,建议 std::ignore 不是为此而设计的,所以实际的解决方案仍然是"(void)强制转换"未使用的变量。

对于 C++17,您还有另一种选择,属性,特别是maybe_unused

// Example program
#include <iostream>
#include <string>
void foo([[maybe_unused]] std::string& color) // 
{
#ifdef PRINT
printf("Printing color: %s", color.c_str());
#else
printf("Not printing any color");
#endif
}
int main()
{ 
std::string color("red");
foo(color);
}

看到它运行

使用(void) variable是避免未使用的变量警告的简单方法,例如:大约assert秒。另一种解决方案是更改打印的定义方式:

#if defined PRINT
#define PRINTF(str) printf("%sn", str)
#else
#define PRINTF(str) (void)str;
#endif