Friday, March 4, 2011

Domain Specific Language in C/C++, does this Kosher?

I was just fooling around with some Domain Specific Language designs for a new project in C/C++ when I thought up this "odd" solution:

 define DSL(...) MakeCommand(#__VA_ARGS__\
                              )->Exec()->GetResults()

 MyResults results = DSL( for p in people do something );

The nice part is this is correct by the standards (but so is a Duff Switch), and cross-platform, portable, etc... However this method is really not any better than writing strings into code, but since the DSL engine parses strings anyways, it seems to look prettier this way, and reduces the clutter. But was wondering what do other folk think about it.

Thanks

From stackoverflow
  • Hmm, while variadic macros are C99, they are not possible in C++. I wouldn't do it like that :) A simple dsl function taking a std::string or whatever string class your framework uses, and returning MakeCommand(str)->Exec()->GetResults() would be my preferred option, since it's more debug friendly, and you can put it into a namespace.

    You will also be able to build up command strings dynamically and pass it to the function. Using your macro approach, passing a str variable would actually pass "str" to the MakeCommand function. You would need another macro for dynamic commands to make it work, which i wouldn't be comfortable with.

    Robert Gould : +1 for the namespace part, that is quite a big point I hadn't though about
    : I'm pretty sure that g++ supports variadic macros.
    Johannes Schaub - litb : littlenag, http://www.comeaucomputing.com/techtalk/#vc :) indeed it supports that. but you use the -Wvariadic-macros to let it warn you about uses of them. (according to its manpage)
    Ben Straub : I can also verify that VC8 and later support variadic macros.

0 comments:

Post a Comment