Template specialization

I don't really understand the part of uppercase. Why would "element+='A'-'a'" make anything uppercase?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// template specialization
#include <iostream>
using namespace std;

// class template:
template <class T>
class mycontainer {
    T element;
  public:
    mycontainer (T arg) {element=arg;}
    T increase () {return ++element;}
};

// class template specialization:
template <>
class mycontainer <char> {
    char element;
  public:
    mycontainer (char arg) {element=arg;}
    char uppercase ()
    {
      if ((element>='a')&&(element<='z'))
      element+='A'-'a'; //How does this make it uppercase? The j turns to J. 
      return element;
    }
};

int main () {
  mycontainer<int> myint (7);
  mycontainer<char> mychar ('j');
  cout << myint.increase() << endl;
  cout << mychar.uppercase() << endl;
  return 0;
}
The ASCII codes for A-Z is 65-90 and a-z is 97-122.

So by computing 'A'-'a' you get the (negative) distance between uppercase and lowercase A in the ASCII table. Note that the distance is the same for any letter. They could have use 'B'-'b', or any other letter, but A was probably used because it's the first letter in the alphabet. To convert between lower and upper case all you need to do is to add or subtract the distance.

Example:
Distance: 'A'-'a' = 65-97 = -32
Element: 'x' = 120
Uppercase: 120-32 = 88 = 'X'
Last edited on
Topic archived. No new replies allowed.