消除未使用变量的警告

#ifndef NEARGYE_NSTD_UNUSED_HPP
#define NEARGYE_NSTD_UNUSED_HPP

namespace nstd {

// Function with varying number of arguments to avoid "unused variable" warnings.
template<typename... Args>
#if defined(__cpp_constexpr) && __cpp_constexpr >= 201304L
constexpr
#else
inline
#endif
void unused(const Args &...) noexcept
{}

} // namespace nstd

#if defined(_MSC_VER)
// Macro with varying number of arguments to avoid "unused variable" warnings.
#  define NSTD_UNUSED(...) ((void)(__VA_ARGS__))
#else
// Macro with varying number of arguments to avoid "unused variable" warnings.
#  define NSTD_UNUSED(...) (decltype(::nstd::unused(__VA_ARGS__))())
#endif

#endif // NEARGYE_NSTD_UNUSED_HPP
#include "unused.hpp"

void foo_unused(int i) {
  NSTD_UNUSED(i); // No warning: NSTD_UNUSED parameter 'i'.
}

int main() {
  int a = 0;
  float b = 0.0f;
  char c[] = "test";
  NSTD_UNUSED(a, b, c); // No warning: NSTD_UNUSED variable 'a', 'b', 'c'.

  int d = 0;
  NSTD_UNUSED(d); // No warning: NSTD_UNUSED variable 'd'.

  return 0;
}

或者使用以下更简便的形式

/** \brief Utility function to eliminate unused variable warnings. */
template<typename ...T> void
ignore(const T&...)
{
}
posted @ 2022-05-13 20:42  卡尔的思索  阅读(81)  评论(0编辑  收藏  举报