My question is about lambda scope for the static member initializers. Consider the following test:
#include <functional>
#include <iostream>
struct S {
static const std::function<void(void)> s_func;
};
const std::function<void(void)> S::s_func = []() {
std::cout << "Hello from " << __PRETTY_FUNCTION__ << std::endl;
};
int main(void) {
S::s_func();
return 0;
}
gcc starting from 4.8 defines the lambda in the scope of S, so the program outputs something like this:
Hello from S::<lambda()>
(gcc-4.8.2 has a different definition for __FUNCTION__ & Co macros, but nevertheless the lambda is still defined within S)
Meanwhile gcc-4.7 defines the lambda in the global scope, so the program outputs
Hello from <lambda()>
Probably newer gcc are more standard-compliant. However I'd like to ask if the standard actually specifies this aspect or it can be implementation-dependent.
Update: as @user5434961 suggested that all __FUNCTION__-alike macros are implementation dependent, so it's better to avoid them in a standard-compliant test. So here is the example which can be compiled if a compiler defines such lambdas within S scope and breaks the compilation otherwise:
#include <functional>
#include <iostream>
struct S {
static const std::function<void(void)> s_func;
private:
static const int s_field;
};
const std::function<void(void)> S::s_func = []() {
std::cout << "Hello from S::s_func. S::s_field = " << S::s_field << std::endl;
};
const int S::s_field = 1;
int main(void) {
S::s_func();
return 0;
}
S::s_fieldto justs_fieldin the updated example? Otherwise, I think it always compiles whatever the scope is.S::s_fieldis private, it can't be accessed from the global scope so the code does break the compilation on GCC-4.7 indeed