在以下代码中,使用折叠表达式创建具有重复元素的数组:
#include <array>
#include <utility>
template <std::size_t N>
class A {
int m_x;
public:
static constexpr std::size_t size = N;
A(int x) : m_x{x} { }
int f() const noexcept { return m_x; }
int g() const noexcept { return m_x * m_x; }
};
template <typename U, std::size_t... I>
auto get_array_impl(const U& m, std::index_sequence<I...>) {
return std::array<int, m.size + 1>{ m.g(), (I, m.f())... };
}
template <typename U, std::size_t... I>
auto get_array(const U& m) {
return get_array_impl(m, std::make_index_sequence<m.size>{});
}
int main()
{
A<3> x{8};
auto a = get_array(x);
return 0;
}
检查它在 Coliru 直播。
编译代码给出警告:
main.cpp:18:50: warning: left operand of comma operator has no effect [-Wunused-value]
18 | return std::array<int, m.size + 1>{ m.g(), (I, m.f())... };
虽然很清楚为什么创建警告(I 实际上被丢弃),但也很明显这不是问题,因为代码并不真正需要 I 值,而是使用可变参数扩展来重复
m.f()
.
如何在仍使用
-Wall
进行编译的同时抑制警告?语法是否有一些变化可以提供相同的结果而不引发警告?
您可以通过使用阻止特定警告的语句来避免编译器警告,例如
#pragma GCC diagnostic ignored "-Wunused-variable"