I had a lot of classes that used a macro with listed fields. The macro was used to serialization, more like MSGPACK_DEFINE. I need a substitution of this mechanism, but I like to used that also keep names of fields.

template< class Visitator>
static inline void runVisit(const char* , Visitator & obj){}

template< class Visitator, class T, class ...Args  >
static inline void runVisit(const char* s, Visitator& obj, T& value, Args&... t)
    int i=0;
    for(; s[0] == ' ' ; ++s)  if( s[0] == 0 ) return;
    for(; s[i] != ',' && s[i] != ' ' ; ++i)  if( s[i] == 0 ) return;
    obj.visit(std::string(s,i), value);
    for(; s[i] != ',' ; ++i)  if( s[i] == 0 ) return;
    runVisit(s+i+1, obj, t...);

#define ACCEPT_AUTO( ... ) \
    template <class Visitator> \
    void accept(Visitator & obj) {\
            runVisit( #__VA_ARGS__ ",",obj, __VA_ARGS__ );\

    template <class Visitator> \
    void accept( Visitator & obj ) const{\
            runVisit( #__VA_ARGS__ ",",obj, __VA_ARGS__ );\

I don't know how this method is efficient, but it takes considerable small amount lines of code. I am interested, if runVisit function can be somehow "tail call" optimized. I don't like the #__VA_ARGS__ parsing, but I don't see simpler way.

Use case example:

Definition of accept method inside some class, that should be Visitable:

class SomeData
    int someField;
    std::string someAnotherField;
    SomeFooData fooField;
    std::vector<SomeBarData> barFieldList;


Can be used by many different visitators:

SomeData data;

SerializerVisitatorAdapter serializer(someStream);

PrinterVisitatorAdapter log(std::cout);

The only thing that Serializer and Printer should have their own implementation of overloaded visit method.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.