我正在探索这个陌生的领域,并想尝试来自 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/