c++ - g++ 可变参数模板。简单示例代码无法编译,提示 'Not a template'

标签 c++ c++11 g++ variadic-templates

我正在探索这个陌生的领域,并想尝试来自 Danny Kalev's tutorial on the matter 的一个简单示例.代码非常简单:

template<> struct Count<> { static const int value = 0;};

template<typename T, typename... Args>
    struct Count<T, Args...> //partial specialization
{ 
    static const int value = 1 + Count<Args...>::value;
};

但是 gcc 4.4.7 甚至 4.7.0 提示(尽管 -std=c++0x -std=gnu++0x 标志):

/src/tests/VTemplates.h:12:8: error: 'Count' is not a template
/src/tests/VTemplates.h:12:18: error: explicit specialization of non-template 'Count'
/src/tests/VTemplates.h:16:8: error: 'Count' is not a template
/src/tests/VTemplates.h:16:26: error: 'Count' is not a template type

我错过了什么?

最佳答案

template<> struct Count<> { static const int value = 0;};

是没有模板参数的模板特化。但是你不能特化一个还不是非特化模板的模板类。换句话说,你必须先建立一个非特化版本的模板类,然后才能特化它。例如,如果您这样做了:

//non-specialized template
template<typename... Args>
struct Count;

//specialized version with no arguments
template<> struct Count<> { static const int value = 0;};

//another partial specialization
template<typename T, typename... Args>
struct Count<T, Args...> 
{ 
    static const int value = 1 + Count<Args...>::value;
};

那行得通。

关于c++ - g++ 可变参数模板。简单示例代码无法编译,提示 'Not a template',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10255038/

相关文章:

c++ - 连接 OpenCV Mat 和单个值

c++ - 在 Bullet 中使用 "mass"

c++ - 移动结构数组 C++

c++ - SFINAE(enable_if)为什么不能用于类模板的成员函数?

c++ - 默认赋值运算符适合 Vector 吗?

c++ - <cstring> 和 <string> 之间的区别

c++ - g++:使用 ZIP 文件作为输入

c++ - 快板更新绘图

c++ - 获取构造函数初始化错误

c++ - C++:使用g++编译opencv和tensorflow时对std::thread的 undefined reference