2

My question is about the following code:

#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;
}

It produces the following compiler warning with MSVC (Visual Studio 2017 15.9.11, v141 toolset, /std:c++17):

warning C4100: 'f': unreferenced formal parameter

It's reproducible on Godbolt: https://godbolt.org/z/6gLDzu

Is this a compiler bug? I was going to report it to Microsoft, but then felt like asking for the community's opinion, maybe I'm missing something? The code does work and the functor is invoked the correct number of times, so it's not the case of the compiler mis-compiling the code and optimizing f out erroneously.

pablo285
  • 2,460
  • 4
  • 14
  • 38
Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335

1 Answers1

3

In the last iteration of your static_for() First + 1 equals Last. This causes the body of the function to vanish and f is unused.

pablo285
  • 2,460
  • 4
  • 14
  • 38