【问题标题】:Suppress warning "expression result unused" on a index_sequence在 index_sequence 上抑制警告“未使用的表达式结果”
【发布时间】:2020-09-03 21:24:22
【问题描述】:

这个问题的灵感来自this answer

以下代码会产生未使用值的警告:

#include <array>
#include <vector>
#include <iostream>
#include <utility>

template <size_t... I>
auto f(std::index_sequence<I...>)
{
  std::array<std::vector<int>, sizeof...(I)> res{(I, std::vector<int>(3, -1))...};
  return res;
}

int main()
{
  auto v = f(std::make_index_sequence<2>{});
  for (const auto& vec : v)
    {
      for (const auto& x : vec)
        std::cout << x << ' ';
      std::cout << '\n';
    }

  return 0;
}

live on Coliru

gcc 10.1.0 的警告是

main.cpp:9:52: warning: left operand of comma operator has no effect [-Wunused-value]

    9 |   std::array<std::vector<int>, sizeof...(I)> res{(I, std::vector<int>(3, -1))...};

      |                                                  ~~^~~~~~~~~~~~~~~~~~~~~~~~~~

clang 10.0.1 警告是

main.cpp:9:51: warning: expression result unused [-Wunused-value]
  std::array<std::vector<int>, sizeof...(I)> res{(I, std::vector<int>(3, -1))...};

(以及一些类似的)。

c++17 中,[[maybe_unused]] 属性应该允许禁止对未使用的变量发出警告。但是,将[[maybe_unused]] 放在f 的参数之前

auto f([[maybe_unused]] std::index_sequence<I...>)

没有效果。

如何抑制上述警告?

【问题讨论】:

    标签: attributes c++17 suppress-warnings


    【解决方案1】:

    您可以将 I 转换为 void 以丢弃表达式,并随之发出警告:

    std::array<std::vector<int>, sizeof...(I)> res{
        (static_cast<void>(I), std::vector<int>(3, -1))...
    };
    

    【讨论】:

    • 非常感谢!根据this answer,转换为void 似乎定义明确。我不清楚警告有什么区别,因为您已经使用逗号运算符丢弃了该值。
    • @francesco 太棒了!这些警告只是为了让您注意可能是错误的事情。当你施放时,你会说“我知道我在做什么”。
    猜你喜欢
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 2011-03-19
    相关资源
    最近更新 更多