简体   繁体   中英

How can I have the effect of default parameter with variadic template

I am hitting this problem for some time now and I can't figure out how to solve it. The context is a reflection system in c++. A slim down explication of the problem is this. I have those 2 structs. One is to represent multiple parents of the type ClassType and the other would represent and Orphan class (a class of ClassType type and without parents)

template<typename ClassType, typename... ParentTypeList>
struct Parents 
{
};

template<typename ClassType>
struct Parents<ClassType>
{        
};

Then in the declaration of my classes to be reflected i use this macro, the class ReflectionHelper::Parents are the classes above

#define DEFINE_METACLASS(className, ...) \
private: \
typedef className SelfType; \
typedef ReflectionHelper::Parents<SelfType, __VA_ARGS__ > ParentList \

A usage of an orphan class it would be:

class TestMetaClassDefine
{
DEFINE_METACLASS(TestMetaClassDefine);     
};

Now the problem is that the __VA_ARGS__ is empty and the

typedef ReflectionHelper::Parents<SelfType, __VA_ARGS__ > ParentList;

is thus not valid.

One way I thought of solving this is to have default template arguments but it is not allowed with variadic template.

Anybody have a technique to resolve this problem?

Thanks alot

The GCC preprocessor allows for a special syntax that elides the final comma in a variadic macro argument list if the list is empty:

#define MACRO(arg, ...) foo(arg, ##__VA_ARGS__)

This exapands:

MACRO(a,b)   ->  foo(a, b)
MACRO(a)     ->  foo(a )

You can use this for your DEFINE_METACLASS macro to cover all cases at once.

Update: As @Dennis says, you can use your original syntax in MSVC++ and it won't even produce a trailing comma.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM