简体   繁体   中英

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. 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

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:

 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? 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). 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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