2

I found what seems to be a compiler bug in Visual Studio 2019 (toolset v142). Here's a minimal piece of code to test for yourself:

#include <functional>
#include <vector>
#include <iostream>

int main()
{
    auto someLamb = [&]()
    {
        enum EnumA { eFoo = 0, eBar = 1, eCount = 2 };
        enum EnumB { eUndefined = -1, eFirst = 0 };
        std::vector<EnumB> edgesChanges;
        edgesChanges.push_back(EnumB::eUndefined);
        edgesChanges.push_back(EnumB::eUndefined);

        auto innerLamb = [&]()
        {
            int a = edgesChanges[EnumA::eFoo];
            int b = EnumB::eFirst;
            int c = edgesChanges[EnumA::eBar];
            int d = EnumB::eFirst;
            return a == b || c == d;
        };
        std::cout << "Hello World!\n" << innerLamb();
    };
    someLamb();
}

I get this in the output:

error C2440: '<function-style-cast>': cannot convert from 'initializer list' to 'main:: 
<lambda_82d455ec4380498d1fafa4212566d992>::()::<lambda_02e80f24e36a566682364f879a75c75d>'

message : No constructor could take the source type, or constructor overload resolution was ambiguous

Notice that the lambdas are nested. If the outer lambda is removed, it compiles fine. Am I doing something wrong?

Timur Nuriyasov
  • 359
  • 2
  • 16
  • For that to work you'll need to compile with `/std:c++latest`. I'm not sure if I should make that into an answer or not because I can't find an explanation for it. – Ted Lyngmo Oct 05 '20 at 10:08
  • I am aware of the `/std:c++latest` thing, but unfortunately I can't rely on a changing code standard in a production environment. I was just wondering if there was _something_ I missed – Timur Nuriyasov Oct 05 '20 at 10:13
  • I don't see anything wrong with what you've done and I can't find anything in the [C++ compiler support](https://en.cppreference.com/w/cpp/compiler_support) list that could explain MSVC's behavior. What C++ standard are you using? C++14 or C++17? – Ted Lyngmo Oct 05 '20 at 10:16
  • 1
    One workaround could be to define the `enum`s outside the lambda. That seems to work in MSVC in both C++14 and C++17 mode. [example](https://godbolt.org/z/e91b34) – Ted Lyngmo Oct 05 '20 at 10:47
  • 2
    a more minimal example would be https://godbolt.org/z/ooWPzM seems to be capturing an instance of an enum declared inside a lambda that causes the problem – Alan Birtles Oct 05 '20 at 10:51

0 Answers0