C++ 模板 : When to include template parameters in templatized struct?

标签 c++ templates struct

我是 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/

相关文章:

c++ - operator== 是友元时的链接器错误

javascript - 如何停止在 node.js 中获取此 ReferenceError?

C++段错误(核心转储)和使用结构

c - 如何在 C 中使用带有嵌套结构的指定 init ?

c++ - 在 C++ 中从 cin 按下 ESC 按钮之前如何读取符号

c++ - 内核驱动程序读取内存未发送整个字符串

c++ - 从 QThread 显示 QMessageBox

c++ - 如何为 C++ 程序定义 MSYS Makefile 的路径?

C++和const reference to temporary binding问题(在C++0X中实现D语言传值传引用规则)

c - 结构体中的整数设置为零