如何使用可变参数模板来实现默认参数的效果
我遇到这个问题已经有一段时间了,但我不知道如何解决。上下文是c++中的反射系统。这个问题的简单解释是这样的。我有那两个结构。一个是表示 ClassType 类型的多个父级,另一个表示孤儿类(ClassType 类型且没有父级的类)
template<typename ClassType, typename... ParentTypeList>
struct Parents
{
};
template<typename ClassType>
struct Parents<ClassType>
{
};
然后在要反映的类的声明中我使用这个宏,类 ReflectionHelper::Parents 是上面的类
#define DEFINE_METACLASS(className, ...) \
private: \
typedef className SelfType; \
typedef ReflectionHelper::Parents<SelfType, __VA_ARGS__ > ParentList \
孤儿类的用法是:
class TestMetaClassDefine
{
DEFINE_METACLASS(TestMetaClassDefine);
};
现在的问题是 __VA_ARGS__ 是空的,
typedef ReflectionHelper::Parents<SelfType, __VA_ARGS__ > ParentList;
因此无效。
我想到解决这个问题的一种方法是使用默认模板参数,但可变参数模板不允许这样做。
有人有解决这个问题的技术吗?
多谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
GCC 预处理器允许使用一种特殊语法,如果列表为空,则可以省略可变宏参数列表中的最后一个逗号:
这扩展了:
您可以将其用于
DEFINE_METACLASS
宏,以一次性涵盖所有情况。更新:正如@Dennis所说,您可以在MSVC++中使用原始语法,它甚至不会产生尾随逗号。
The GCC preprocessor allows for a special syntax that elides the final comma in a variadic macro argument list if the list is empty:
This exapands:
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.