【问题标题】:Fixing "-Wunused-parameter" warning which depends on pre-processor conditions修复取决于预处理器条件的“-Wunused-parameter”警告
【发布时间】:2020-06-16 11:22:41
【问题描述】:

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

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

我见过 (void) like 的用法:

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

这是正确的方法吗?

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

【问题讨论】:

  • 如果可能的话,我建议您使用正常的 if 条件。这当然要求 PRINT 始终定义为真值或假值。

标签: c++ c++11 c++14 c-preprocessor compiler-warnings


【解决方案1】:

我真的更喜欢用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 has not been designed for that,所以实际的解决方案应该仍然是“(void) cast”未使用的变量。

使用 C++17,您还有另一种选择,attributes,尤其是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);
}

See it running

【讨论】:

    【解决方案2】:

    使用(void) variable 是一种避免未使用变量警告的简单方法,例如:asserts 附近。另一种解决方案是更改 print 的定义方式:

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

    【讨论】:

      猜你喜欢
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      相关资源
      最近更新 更多