修复"-Wunused-parameter"取决于预处理器条件的警告
Fixing "-Wunused-parameter" warning which depends on pre-processor conditions
当变量的使用取决于预处理器指令(#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
相关文章:
- 警告处理为错误这里有什么问题
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- cppcheck在const std::string[]上引发警告
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 基于模板值的条件变量
- GCC对可能有效的代码抛出init list生存期警告
- 修复"-Wunused-parameter"取决于预处理器条件的警告
- 为什么C++中没有无用的条件回报警告
- 警告 634:相等或有条件的强类型不匹配(类型"bool")
- 为什么通过条件操作员将参考传递到初始化列表会导致警告
- 是“警告 C4127”(条件表达式是常量)曾经有帮助
- 警告:条件的第二个/第三个操作数不起作用 [-Wunused-value]
- 如何避免模板代码中编译时常量条件"conditional expression is constant"警告?
- 警告C4127:cl命令中的条件表达式为常量
- 警告 C4127:条件表达式是常量