We're not allowed to define a functor struct inside a function because one is not allowed to use function declared structs in the instantiation of function templates.
Are there any other significant pitfalls to be aware of? E.g. would this be bad:
int foo()
{
struct Scratch
{
int a, b, c;
};
std::vector<Scratch> workingBuffer;
//Blah Blah
}
1. C++ standard forbids using locally-defined classes with templates.
14.3.1/2: A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.
A code example:
Here is a little more reference from IBM documentation:
2. Declarations in a local class can only use type names, enumerations, static variables from the enclosing scope, as well as external variables and functions.
A Code Example:
3. A local class cannot have static data members
A Code Example:
local structs are perfectly legal, even in C++98. You cannot use them with templates in C++98 though, whereas you can in C++0x. g++ 4.5 supports using local structs with templates in -std=c++0x mode.
The scope of the local classes is the function in which they're defined.But that isn't interesting in itself1.
What makes local classes interesting is that if they implement some interface, then you can create instances of it (using
new
) and return them, thereby making the implementation accessible through the base class pointer even outside the function.Some other facts about local classes:
They cannot define static member variables.
They cannot access nonstatic "automatic" local variables of the enclosing function. But they can access the
static
variables.They can be used in template functions. They cannot be used as template argument, however.
If they defined inside template function, then they can use the template parameters of the enclosing function.
Local classes are final, that means users outside the function cannot derive from local class to function. Without local classes, you'd have to add an unnamed namespace in separate translation unit.
Local classes are used to create trampoline functions usually known as thunks.
Some references from the Standard (2003)
9.8 Local class declarations [class.local]
Yes. Local classes can't be used as template parameters in C++03
Local structs / classes can't have static data members, only static member functions. Also, they can't be templates.