Can a lambda have extern "C" linkage?
This seems to 开发者_Go百科work on the platforms I have tried:
#include <iostream>
// extern "C" linkage
extern "C" void foo(void (*fn_ptr)(int));
namespace {
struct bar {
static void f(int);
};
}
int main() {
// Usually works on most platforms, not guaranteed though:
foo(bar::f);
// Probably equally bad or worse?
foo([](int x) { std::cout << x << std::endl; });
}
but then again passing a static member function also worked on these platforms when it was not required to.
Is there a way to force a lambda to have suitable linkage to make this safe and portable? Or is it already?
No. Lambdas are ultimately objects that have a function call operator. A captureless lambda can be converted into a function pointer of its appropriate type, but that function pointer will be a C++ function with C++ linkage.
精彩评论