#include <iostream>
#include <string>
usingnamespace 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() {
returnthis->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.