I l@ve RuBoard |
![]() ![]() |
2.3 Local ClassesLocal classes are an interesting and little-known feature of C++. You can define classes right inside functions, as follows: void Fun() { class Local { ... member variables ... ... member function definitions ... }; ... code using Local ... } There are some limitations—local classes cannot define static member variables and cannot access nonstatic local variables. What makes local classes truly interesting is that you can use them in template functions. Local classes defined inside template functions can use the template parameters of the enclosing function. The template function MakeAdapter in the following code adapts one interface to another. MakeAdapter implements an interface on the fly with the help of a local class. The local class stores members of generic types. class Interface { public: virtual void Fun() = 0; ... }; template <class T, class P> Interface* MakeAdapter(const T& obj, const P& arg) { class Local : public Interface { public: Local(const T& obj, const P& arg) : obj_(obj), arg_(arg) {} virtual void Fun() { obj_.Call(arg_); } private: T obj_; P arg_; }; return new Local(obj, arg); } It can be easily proven that any idiom that uses a local class can be implemented using a template class outside the function. In other words, local classes are not an idiom-enabling feature. On the other hand, local classes can simplify implementations and improve locality of symbols. Local classes do have a unique feature, though: They are final. Outside users cannot derive from a class hidden in a function. Without local classes, you'd have to add an unnamed namespace in a separate translation unit. Chapter 11 uses local classes to create trampoline functions. |
I l@ve RuBoard |
![]() ![]() |