How do I repeat "template <class T>" less?

I am teaching myself templates in C++ classes and functions. The following code runs as expected, printing out "5" and then "Ned".

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
#include <iostream>
#include <string>
using namespace std;

template <class T>
class Person {
  T identifier;
  public:
    Person(T);
    T getIdentifier();
};

template <class T>
Person<T>::Person(T id) {
  this->identifier = id;
}

template <class T>
T Person<T>::getIdentifier() {
  return this->identifier;
}

int main() {
  Person<int> a(5);
  Person<string> b("Ned");

  cout << a.getIdentifier() << endl;
  cout << b.getIdentifier() << endl;
}


However, I repeat `template <class T>` so many times. I repeat it not only in the initial class declaration, but also before every time I define a method in the `Person` class.

Had the template parameters been more complex (say `template <class T, class U, class V>`), changing the template parameters in one foul swoop would have required a lot of copying and pasting.

How do I repeat `template <class T>` less in the above code? Also, why is the notation `template <class T>` as opposed to just `template <T>`?
If you are defining a template member outside a class you should repeat the template parameter list.
As for your second question then T in the record template <T> can be a non-type parameter. For example

typedef int T;
template <T> class SomeClass;

So to distiguish type parameters from non-type parameters keyword class or typename is used for type parameters.
Last edited on
Topic archived. No new replies allowed.