Reputation: 1876
One of our projects involves generating boilerplate code for classes.
For example, given a text file with multiple definitions like:
STRUCT Foo
{
int i;
float f;
string s;
}
a Perl script will create a header file with multiple declarations like:
struct Type_Foo : BaseType
{
int i;
float f;
string s;
Generated_Foo();
void clear();
bool equals(Generated_Foo const&) const;
string const* toTraceString() const;
string const* toXmlString() const;
string const* toJsonString() const;
bool fromXmlString(char const*);
bool fromJsonString(char const*);
};
and a corresponding cpp file with the implementations.
My question is:
Is it possible to achieve a similar result (modulo syntax differences) without the precompiler stage?
Thank you!
Upvotes: 1
Views: 69
Reputation: 58402
Boost.Preprocessor can do this, just by (ab)using the C/C++ preprocessor. It could look something like this.
#include <boost/preprocessor/seq/for_each.hpp>
#define STRUCT_MEMBER(r, data, elem) elem;
#define STRUCT(structname, seq) \
struct Type_ ## structname : BaseType { \
BOOST_PP_SEQ_FOR_EACH(STRUCT_MEMBER, _, seq) \
Generated_ ## structname(); \
void clear(); \
bool equals(Generated_Foo const&) const; \
string const* toTraceString() const; \
string const* toXmlString() const; \
string const* toJsonString() const; \
bool fromXmlString(char const*); \
bool fromJsonString(char const*); \
}
STRUCT(Foo, (int i)(float f)(string s));
Having worked with Boost.Preprocessor, my opinion is that, although it's very cool and can be useful to do everything within C++, it can quickly get complicated for nontrivial uses. If you already have a good, working external code generator (like your Perl scripts), there's nothing wrong with continuing to use it.
Upvotes: 1