简体   繁体   English

C ++模板:何时在模板化结构中包含模板参数?

[英]C++ Templates: When to include template parameters in templatized struct?

I'm new to C++ and templates and I'm having trouble with this concept. 我是C ++和模板的新手,我对这个概念感到困惑。 I had a question about this implementation of the C++11 is_same feature, written by Dirk Holsopple here: https://stackoverflow.com/a/13071396/5199724 我对Dirk Holsopple在此处编写的C ++ 11 is_same功能的实现有疑问: https ://stackoverflow.com/a/13071396/5199724

This is his code, which compiles: 这是他的代码,编译如下:

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

My question is, why is this not valid: 我的问题是,为什么这是无效的:

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

The inclusion of template parameters in both struct declarations would make intuitive sense to me, but the second code block gives me the following errors in Visual Studio: 对我来说,在两个struct声明中都包含模板参数对我来说很直观,但是第二个代码块在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

So why would template parameters be needed in Line 7 but not in Line 2? 那么,为什么在第7行而不是在第2行中需要模板参数? What is the general rule for when to include template parameters? 何时包括模板参数的一般规则是什么? Thanks for your help! 谢谢你的帮助!

template<class T>
struct is_same<T, T> {
  enum { value = 1 };
};

The reason why this is not valid is because this is a template specialization, and you can't specialize something that doesn't exist (is_same). 之所以无效,是因为这是模板专门化,您不能专门化不存在的内容(is_same)。 First you have to create the primary template, then specialize it. 首先,您必须创建主模板,然后对其进行专门化。

The first one is a template-definition, where the template-keyword already says it will be a template. 第一个是模板定义,其中template-keyword已经说过它将是一个模板。

The second is a template specialization. 第二个是模板专业化。 It is a template as well, but the parameters must match the previous declared definition. 它也是一个模板,但是参数必须与先前声明的定义匹配。

Eg in 例如

template<typename S, typename T, typename U>
struct whatever{};

template<typename V, typename W>
struct whatever<V, W, W>{};

you need to specify which parameter of the specialisation (V,W) matches which parameter of the definition (S,T,U). 您需要指定专业化(V,W)的哪个参数与定义(S,T,U)的哪个参数匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM