我是 C++ 和模板的新手,我在这个概念上遇到了麻烦。我有一个关于 C++11 is_same 功能的实现的问题,由 Dirk Holsopple 在此处编写:https://stackoverflow.com/a/13071396/5199724
这是他的代码,可以编译:
1 template<class T, class U>
2 struct is_same {
3 enum { value = 0 };
4 };
5
6 template<class T>
7 struct is_same<T, T> {
8 enum { value = 1 };
9 };
我的问题是,为什么这无效:
1 template<class T, class U>
2 struct is_same<T, U> { // template parameters in struct declaration -- not valid?
3 enum { value = 0 };
4 };
5
6 template<class T>
7 struct is_same<T, T> {
8 enum { value = 1 };
9 };
在两个结构声明中包含模板参数对我来说很直观,但第二个代码块在 Visual Studio 中给我以下错误:
error C2143: syntax error : missing ';' before '<'
error C2059: syntax error : '<'
error C2334: unexpected token(s) preceding '{'; skipping apparent function body
error C3412: cannot specialize template in current scope
那么为什么第 7 行需要模板参数而第 2 行不需要呢?何时包含模板参数的一般规则是什么?感谢您的帮助!
最佳答案
第一个是模板定义,模板关键字已经说明它将是一个模板。
第二个是模板特化。它也是一个模板,但参数必须与先前声明的定义匹配。
例如在
template<typename S, typename T, typename U>
struct whatever{};
template<typename V, typename W>
struct whatever<V, W, W>{};
您需要指定特化 (V,W) 的哪个参数与定义 (S,T,U) 的哪个参数相匹配。
关于C++ 模板 : When to include template parameters in templatized struct?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35298501/