Search code examples
c++variadic-macros

How to write a macro that will be expanded to define an object with template parameters


Is it possible to write a macro, which, in turn, creates an object definition from it, for example:

DEFINE_OBJECT_INVALID_VALUES(ObjectType, double, int, 1.0, 1) 

should become:

ObjectType a<double, int>(1.0, 1);

and

DEFINE_OBJECT_INVALID_VALUES(ObjectType, double, int, bool, 1.0, 1, false) 

should become:

ObjectType a<double, int, bool>(1.0, 1, false);

Solution

  • You can overload a macro on number of arguments:

    #define DEFINE_OBJECT_INVALID_VALUES_2(T1, V1)  \
            a<T1>(V1)
    #define DEFINE_OBJECT_INVALID_VALUES_4(T1, T2, V1, V2)  \
            a<T1, T2>(V1, V2)
    #define DEFINE_OBJECT_INVALID_VALUES_6(T1, T2, T3, V1, V2, V3)  \
            a<T1, T2, T3>(V1, V2, V3)
    #define DEFINE_OBJECT_INVALID_VALUES_N(_1,_2,_3,_4,_5,_6,_7,_8,_9,N,...)  \
            DEFINE_OBJECT_INVALID_VALUES_##N
    #define DEFINE_OBJECT_INVALID_VALUES(objecttype, ...)  \
            objecttype DEFINE_OBJECT_INVALID_VALUES_N(__VA_ARGS__,9,8,7,6,5,4,3,2,1)(__VA_ARGS__)
    
    // will expand to:
    // ObjectType a<double, int>(1.0, 1)
    DEFINE_OBJECT_INVALID_VALUES(ObjectType, double, int, 1.0, 1) 
    
    // will expand to:
    // ObjectType a<double, int, bool>(1.0, 1, false)
    DEFINE_OBJECT_INVALID_VALUES(ObjectType, double, int, bool, 1.0, 1, false)