I'm learning C++ and ran into a compile error using Visual C++ 2005
Express on the following example program (located at
http://www.cplusplus.com/doc/tutorial/templates.html):
// template specialization
#include <iostream>
using namespace std;
template <class T>
class container {
T element;
public:
container (T arg) {element=arg;}
T increase () {return ++element;}
};
template <>
class container <char{
char element;
public:
container (T arg) {element=arg;}
char uppercase ();
};
template <>
char container<char>::uppercase()
{
if ((element>='a')&&(element<='z'))
element+='A'-'a';
return element;
}
int main () {
container<intmyint (7);
container<charmychar ('j');
cout << myint.increase() << endl;
cout << mychar.uppercase() << endl;
return 0;
}
The compile errors:
Compiling...
template4.cpp
..\template4.cpp(17) : error C2146: syntax error : missing ')' before
identifier 'arg'
..\template4.cpp(17) : error C2146: syntax error : missing ';' before
identifier 'arg'
..\template4.cpp(17) : error C2460: 'container<char>::T' : uses
'container<char>', which is being defined
.\template4.cpp(19) : see declaration of 'container<char>'
..\template4.cpp(17) : error C2059: syntax error : ')'
..\template4.cpp(17) : error C4430: missing type specifier - int
assumed. Note: C++ does not support default-int
..\template4.cpp(17) : error C2473: 'arg' : looks like a function
definition, but there is no parameter list.
..\template4.cpp(17) : error C2065: 'arg' : undeclared identifier
..\template4.cpp(17) : error C4430: missing type specifier - int
assumed. Note: C++ does not support default-int
..\template4.cpp(17) : error C2864: 'container<char>::element' : only
static const integral data members can be initialized within a class
..\template4.cpp(18) : error C2628: 'container<char>' followed by 'char'
is illegal (did you forget a ';'?)
..\template4.cpp(19) : error C2059: syntax error : '}'
..\template4.cpp(19) : error C2143: syntax error : missing ';' before
'}'
..\template4.cpp(19) : error C2059: syntax error : '}'
..\template4.cpp(22) : error C2039: 'uppercase' : is not a member of
'container<char>'
.\template4.cpp(19) : see declaration of 'container<char>'
..\template4.cpp(27) : error C2912: explicit specialization; 'char
uppercase(void)' is not a specialization of a function template
..\template4.cpp(24) : error C2065: 'element' : undeclared identifier
..\template4.cpp(31) : error C2664: 'container<char>::container(const
container<char&)' : cannot convert parameter 1 from 'char' to 'const
container<char&'
Reason: cannot convert from 'char' to 'const container<char>'
No constructor could take the source type, or constructor
overload resolution was ambiguous
..\template4.cpp(33) : error C2039: 'uppercase' : is not a member of
'container<char>'
.\template4.cpp(19) : see declaration of 'container<char>'
Could someone help me to clarify what the problem is?
TIA