c++ - 关于未使用变量的奇怪编译器警告,这是编译器错误吗?
问题描述
我的问题是关于以下代码:
#include <type_traits>
#include <utility>
template <int First, int Last, typename Functor>
constexpr void static_for(Functor&& f)
{
if constexpr (First < Last)
{
f(std::integral_constant<int, First>{});
static_for<First + 1, Last, Functor>(std::forward<Functor>(f));
}
}
int main() {
static_for<1, 3>([](int /*i*/){
});
return 0;
}
它使用 MSVC(Visual Studio 2017 15.9.11、v141 工具集、/std:c++17)产生以下编译器警告:
警告 C4100:“f”:未引用的形式参数
它可以在 Godbolt 上重现:https ://godbolt.org/z/6gLDzu
这是编译器错误吗?我打算向微软报告,但后来想征求社区的意见,也许我遗漏了什么?代码确实有效,并且仿函数被调用了正确的次数,因此编译器不会错误地编译代码并f
错误地优化。
解决方案
在你的最后一次迭代中static_for()
First + 1
equals Last
。这会导致函数体消失并且f
未被使用。
推荐阅读
- disk - 调整阿里云数据盘大小
- java - 如何生成一个没有任何重复的随机数数组(在Java中)?
- .net - EF Core linq and conditional include and theninclude problem
- java - 将 ehCache 3 ehcache.xml 放在 Springboot 2 (Spring 5 ) 项目的 jar 文件之外
- ruby-on-rails - Ruby / Rails 等待 redirect_to 解决并根据响应执行某些操作
- node.js - 如何在变量中捕获获取请求数据?
- c# - uwp c#, is it possible to refer single variable for different types of control?
- c++ - QMovie webp frame stutters
- c++ - 访问类 c++ 中的私有结构
- android - custom list view with edit text in fragment