Search code examples
c++c++11boost

boost pp repeat to forward declare classes


In short, I would like to accomplish the following:

#define CLASS( C ) class C;
#define CLASSES( ... )

CLASSES( Foo, Bar, Golf )    // Expand: class Foo; class Bar; class Golf;

Is there any way to accomplish this using boost?

Currently, I have tried the following:

#include <boost/preprocessor/repetition/repeat.hpp>

#define CLASS( C ) class C;

#define CLASSES( N, ... ) BOOST_PP_REPEAT( N, CLASS, Name) // problem here

CLASSES( 3, Foo, Bar, Golf ) // Expand: class Name; class Name; class Name;

But I don't know how to incorporate __VA_ARGS__ in order to expand different names.

I am open to other suggestions, not strict on boost, but restricted to C++11.


Solution

  • Here's a BOOST PP example using CLASSES(x, y, z) to expand to class forward declaration statements.

    #include <boost/preprocessor/library.hpp> // The whole BOOST_PP library (overkill).
    
    #define CLASSES_SEMI() ;
    
    #define CLASSES_OP(r, data, i, elem) \
        BOOST_PP_IF(i, CLASSES_SEMI, BOOST_PP_EMPTY)() \
        class elem \
        /**/
    
    #define CLASSES_SEQ(seq) \
        BOOST_PP_SEQ_FOR_EACH_I(CLASSES_OP, /*no data*/, seq) \
        /**/
    
    #define CLASSES(...) CLASSES_SEQ(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))
    
    CLASSES(Foo, Bar, Golf);
    

    Generates:

    class Foo ; class Bar ; class Golf ;