首页 > 解决方案 > 关于未使用变量的奇怪编译器警告,这是编译器错误吗?

问题描述

我的问题是关于以下代码:

#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错误地优化。

标签: c++visual-c++c++17

解决方案


在你的最后一次迭代中static_for() First + 1equals Last。这会导致函数体消失并且f未被使用。


推荐阅读