A recent build of GCC 4.8 gives the following code, when in a header file:
auto L = [](){};
struct S
{
decltype(L) m;
};
the following warning:
test.hpp:3:8: warning: 'S' has a field 'S::m' whose type uses the anonymous namespace [enabled by default]
struct S
^
Why does the compiler consider the type of the lambda to use the anonymous namespace? I made the lambda global, I didn’t use an anonymous namespace anywhere.
UPDATE: The compiles gives the same warning even if I put the lambda in an explicit namespace, like so:
namespace N
{
auto L = [](){};
}
struct S
{
decltype(N::L) m;
};
UPDATE 2: In fact, it seems even class scope lambdas have the same problem:
class N
{
static constexpr auto L = [](){};
};
struct S
{
decltype(N::L) m;
};
GCC’s warning may have been a bit confusing, but its intention is certainly right. The type of the lambda is unnamed, and it is unique in the whole program. On the other side if your class isn’t put in an unnamed namespace (which it, given your description, I suppose is not), your class is the same type in every translation unit that you include it into. Since the same class should have the same members, and not different members in different translation units, this is a violation (and leads to undefined behavior).
What’s at least as bad is that
Lisextern, so that you will get “multiple definitions of L” linker errors once you include the header into multiple translation units.