6

The C++11 standard says (or at least, the version I have - not the final one) :

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator.

I understand why it is not possible to get a function pointer from a stateful lambda since a function pointer cannot hold any data by itself.

But when the captured objects are just a static members /static variable, there is no such limitation since the references to the captured objects can be hardwired in the function itself.

struct A {
    static int count = 0;
    void foo() {
         static int bar = 0;
         auto fun = [&]()->void {
             count++;
             bar++;
         };
         void(*ptrFun)();
         ptrFun = fun; // forbidden by the quoted wording
    }
};

Why isn't it always possible to convert a lambda to a function pointer as soon as the former is stateless ? Am I missing something or does the committee forgot this specific point ?

4

1 回答 1

9

A::count does not need to be captured at all. Only this and local variables need to be captured. Variables with static storage duration (e.g., static data members, namespace-scope variables, or function-local static variables) do not need to be captured because they are "unique." There is exactly one instance of each such variable, so a reference to the object does not need to be captured.

If you remove the default capture from your lambda (i.e., change [&] to []) and define count, it should compile without error. (I've verified that both Visual C++ 2012 RC and g++ 4.5.1 accept the code; the only change I had to make was to move the inline initialization of count, since neither of those compilers supports that C++11 feature yet.)

于 2012-07-17T23:17:59.493 回答