Topic: identifiers as template arguments and compile-time regexps for code


Author: Colin <google@icemx.net>
Date: Fri, 28 Dec 2007 14:25:24 CST
Raw View
Hallo,

in the last couple of months I have repeatedly stumbled over
limitations in the C++ language, some of which I will try to isolate,
write about, and share for discussion...

(These issues all arose while working on real-life code; the code
snippets below are however mostly not complete, and not real C++
(because they show what I would like to be able to write, i.e. things
that are not currently possible)).

(1) Apart from all the many-discussed shortcomings of enums ... here's
something that I would have liked to be able to write on several
occasions:

enum foo {
  FOBBLE_FROBNICATE,
  FIZZLE_FROBNICATE,
  FOBBLE_GUNKL,
  ...
};

int bar( const foo f ) {
  switch ( f ) {
    case "FOBBLE_.*":
      return 1;
    case "FIZZLE_.*":
      return 42:
    default:
      throw "argh";
  }
}

I.e., I want the compiler to look at the definition of foo and expand
the regular expression in the given case labels to all enum constants
whose names match that regular expression.

(2) Suppose that we allow access to matched sub-expressions; that way
we could finally write ONE simple function that converts ANY enum
value to its name:

template< typename Enum >
std::string to_string( const Enum e ) {
  switch ( e ) {
    case "(.*)":
      return # \\1;  // some syntax to allow access to the bracketed
sub-expressions of the supplied regular expression and convert it to a
string
    default:
      return boost::lexical_cast< std::string >( int( e ) );
  }
}

(3) Now if only we could add identifiers as template parameters we
could do e.g. some more generic forwarding:

template< typename T >
struct foo {
  // structors etc.

  template< identifier I >
  typeof( T::I ) get_ ## I() {
    return t_.I;
  }

  T t_;
};

which becomes really powerful when combined with vararg-templates to
allow arbitrary parameter forwarding (when the forwardee is a
function, not an object as here).

Enough for now; item (2) could of course also be accomplished by some
kind of compile-time introspection; something general enough for
serialisation and persistence of arbitrary objects (without having to
write code for every single class that is to be serialised) is (a)
sorely missing from C++, and (b) should hopefully be able to cover
(2), too.

Regards, Colin

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]