4

我正在探索这个陌生的领域,并认为我会尝试Danny Kalev 关于此事的教程中的一个简单示例。代码非常简单:

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

我错过了什么?

4

1 回答 1

10
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;
};

那会奏效。

于 2012-04-21T00:21:25.933 回答