可变参数模板之谜
这是运行良好的代码:
template<typename... Args> struct count;
template<>
struct count<> {
static const int value = 0;
};
template<typename T, typename... Args>
struct count<T, Args...> {
static const int value = 1 + count<Args...>::value;
};
现在我想知道为什么我们需要部分专门化计数类模板?
我们可以做类似的事情:
template< typename... args> struct dd; // edited according to answer but now getting error redeclared with 2 template parameters which is point below with mark %%
template<>
struct dd<>{
static const int value = 0;
};
template<typename T, typename... args> //%%
struct dd{
static const int value= 1+ dd<args...>::value;
};
但这不起作用,但为什么?
非常感谢任何帮助:)
编辑:根据答案编辑解决方案。
Here is the code that works fine :
template<typename... Args> struct count;
template<>
struct count<> {
static const int value = 0;
};
template<typename T, typename... Args>
struct count<T, Args...> {
static const int value = 1 + count<Args...>::value;
};
now i was wondering why we need to partial specialize the count class template?
Can we do something like :
template< typename... args> struct dd; // edited according to answer but now getting error redeclared with 2 template parameters which is point below with mark %%
template<>
struct dd<>{
static const int value = 0;
};
template<typename T, typename... args> //%%
struct dd{
static const int value= 1+ dd<args...>::value;
};
but this doesn't works but why?
Any help is very appreciated :)
Edit : edited the solution according to answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不是一种特化,
它表示
dd
始终需要至少一个参数。旁注,已经有一种内置方法来获取可变参数模板参数的数量,并且
count
结构可以实现为is not a specialization of
which says
dd
will always require at least one parameter.Sidenote, there already is a built-in way to get the number of variadic template parameters and the
count
struct could be implemented as使用
template
您无法创建省略T
的专业化(即dd<>
) — 包可以为空,但T
不能。因此,您将模板声明为仅需要一个包的模板,专门针对空包来停止递归,并部分专门针对
来解压一种类型并创建一个新的类型包装 (n - 1) 种类型。至于编辑:您不能定义具有不同参数但名称相同的另一个模板,您必须专门化现有的模板。
With
template <typename T, typename... Args>
you can't create a specialisation that omitsT
(i.e.dd<>
) — the pack can be empty, butT
can't. So you declare the template as one that takes only a pack, specialise for empty pack to stop recursion, and partially specialise for<T, Args...>
to unpack one type and create a new pack with (n - 1) types.As for the edit: you can't define another template with different arguments but the same name, you have to specialise the already existing one.