下面是运行良好的代码:
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;
};
但这行不通,但为什么呢?
非常感谢任何帮助:)
编辑:根据答案编辑解决方案。
最佳答案
template<>
struct dd<> {
static const int value = 0;
};
不是
的特化template< typename T,typename... args> struct dd;
表示 dd
总是需要至少一个参数。
旁注,已经有一个内置的方法来获取可变模板参数的数量,count
结构可以实现为
template <class ...args>
struct count
{
static const int value = sizeof...(args);
};
关于c++ - 可变参数模板之谜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7703395/