可变长度模板参数列表? [英] Variable length template arguments list?

查看:168
本文介绍了可变长度模板参数列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得找到这样的东西:

I remember seing something like this being done:

template <ListOfTypenames>
class X : public ListOfTypenames {};

也就是说,X继承自作为模板参数传递的变长字符串类型列表。这个代码是假设的,当然。

that is, X inherits from a variable length list of typenames passed as the template arguments. This code is hypothetical, of course.

但我找不到任何参考。是否可以?是C ++ 0x吗?

I can't find any reference for this, though. Is it possible? Is it C++0x?

推荐答案

你可以在当前的C ++。你给模板一个足够大的参数数量,你给它们默认值:

You can do it in current C++. You give the template a "large enough" number of parameters, and you give them defaults:

class nothing1 {};
class nothing2 {};
class nothing3 {};

template <class T1 = nothing1, class T2 = nothing2, class T3 = nothing3>
class X : public T1, public T2, public T3 {};

或者你可以更复杂和使用递归。首先你声明模板:

Or you can get more sophisticated and use recursion. First you forward-declare the template:

class nothing {};

template <class T1 = nothing, class T2 = nothing, class T3 = nothing>
class X;

然后你专注于所有参数都是默认的情况:

Then you specialise for the case where all the parameters are default:

template <>
class X<nothing, nothing, nothing> {};

然后你正确定义了一般的模板(以前你只有转发声明) p>

Then you properly define the general template (which previously you've only forward-declared):

template <class T1, class T2, class T3>
class X : public T1, public X<T2, T3>

请注意在基类中,如何继承X但是你错过了第一个参数。所以他们都沿着一个地方滑。

Notice how in the base class, you inherit X but you miss the first parameter. So they all slide along one place. Eventually they will all be defaults, and the specialization will kick in, which doesn't inherit anything, thus terminating the recursion.

更新:这是一个默认值,刚刚有一个奇怪的感觉,我之前发布过类似这样的并猜测什么...

Update: just had a strange feeling I'd posted something like this before, and guess what...

这篇关于可变长度模板参数列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆