Restrictions on local classes
17 [temp]
Faisal Vali

Created on 2008-10-05.00:00:00 last changed 137 months ago


Date: 2008-10-05.00:00:00

Now that the restriction against local classes being used as template arguments has been lifted, they are more useful, yet they are still crippled. For some reason or oversight, the restriction against local classes being templates or having member templates was not lifted. Allowing local classes to have member templates facilitates generic programming (the reason for lifting the other restriction), especially when it comes to the visitor-pattern (see the boost::variant documentation and the following example) as implemented in boost and the boost::MPL library (since functors have to be template classes in mpl, and higher-order functors have to have member templates to be useful). A local class with a member template would allow this desirable solution:

    #include <boost/variant.hpp>
    int main() {
      struct times_two_generic: public boost::static_visitor<> {
        template <typename T> void operator()(T& operand) const {
            operand += operand;

      std::vector<boost::variant<int, std::string>> vec;
      vec.push_back("hello ");

      times_two_generic visitor;
      std::for_each(vec.begin(), vec.end(), boost::apply_visitor(visitor));

Is there any compelling reason not to allow this code? Is there any compelling reason not to allow local classes to be templates, have friends, or be able to define their static data members at function scope? Wouldn't this symmetry amongst local and non-local classes make the language more appealing and less embarrassing?

Date User Action Args
2009-03-23 00:00:00adminsetstatus: open -> extension
2008-10-05 00:00:00admincreate