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!