4

Following code is accepted by gcc 6 and clang 4, but MSVC 2017 which claims to support C++14 (and generic lambdas in particular) discards it with error C2894: templates cannot be declared to have 'C' linkage

extern "C" void f() {
    std::vector<int> v { 1, 2, 3 };
    std::for_each(std::begin(v), std::end(v), [](auto& x) {
        x++;
    });
    std::cout << v[0];
}

I understand that generic lambda is internally translated to some structure with templated call-operator but how does it interfere with extern "C"?

Is it a bug in MSVC? Can you suggest a workaround for using generic lambdas in extern "C" functions?

UPDATE

I reported this issue to Microsoft and the response was

Thank you for your feedback! We have determined that this issue is not a bug. See msdn https://msdn.microsoft.com/en-us/library/95bhc9c2.aspx

which doesn't explain much.

rafalc
  • 203
  • 5
  • 9
  • 8
    *"Is it a bug in MSVC?"* - Looks like it. Language linkage for a function should never ever affect what types you can use inside the function body. – StoryTeller - Unslander Monica Aug 09 '17 at 12:25
  • 6
    You can still forward implementation to a not `extern C` function as work-around. – Jarod42 Aug 09 '17 at 12:26
  • 1
    @Jarod42, thank you, I managed to find another work-around that doesn't involve a helper function. It turns out that if you separate declaration of `f` (with `extern "C"`) from definition MSVC does not complain. – rafalc Aug 10 '17 at 18:10

0 Answers0