Search code examples
visual-studiotemplateslambdac++14generic-lambda

MSVC lambda with two auto params of same type


It seems that Visual Studio behaves differently from GCC and Clang given the following code:

auto f2 = [](auto x, decltype(x) y)
{
  return x + y;
};
f2(1, 2);

Clang and GCC will accept this, but MSVC will complain with the message

error C3536: 'x': cannot be used before it is initialized

Is there a workaround in order to force the 2 parameters types to be equal?

Nb : this problem can be reproduced with Visual Studio 2015, 2017 and Pre-2018

See this code on compiler explorer (where you can switch between different compilers)


Edit:

The behavior of this code is not what one might expect when reading it: it will compile whenever decltype(y) is convertible to decltype(x), and not only when they are equal.

So, both @n.m. and @max66 answers are correct: the first is if you want to force the types to be equal, and the second is if you want to work with is_convertible.

I have accepted the second, since it preserves the original code behavior (although, the original code was probably erroneous : a comparison on type equality was better in my case)


Solution

  • Not exactly what you asked but... maybe you can impose it inside the lambda, using another lambda

    auto f2 = [] (auto x, auto y)
     { return [](decltype(x) a, decltype(x) b) {return a + b;}(x, y); };