CS253: Software Development with C++

Spring 2022

Template Implementation

Show Lecture.TemplateImplementation as a slide show.

CS253 Template Implementation

Pick One

Inline

#include <iostream>

template<typename T>
class Foo {
    T data;
  public:
    Foo(const T &value) : data(value) { }
    T get() const { return data; }
};

template<typename T>
std::ostream & operator<<(std::ostream &os, const Foo<T> &f) {
    return os << f.get();
}

Not Inline

#include <iostream>

template<typename T>
class Bar {
    T data;
  public:
    Bar(const T &);
    T get() const;
};

template<typename T>
Bar<T>::Bar(const T &value) : data(value) {
}

template<typename T>
T Bar<T>::get() const {
    return data;
}

template<typename T>
std::ostream & operator<<(std::ostream &os,
                          const Bar<T> &b) {
    return os << b.get();
}

Example

from ~cs253/Example/Templates:

$ cp ~cs253/Example/Templates/* .
$ ls
Bar.h  Foo.h  index.php  Makefile  test.cc
$ cat test.cc
#include "Foo.h"
#include "Bar.h"
#include <iostream>
int main() {
    Foo<short> f(12);
    Bar<long> b(34);
    std::cout << f << ' ' << f.get() << ' ' << sizeof(f) << '\n'
	      << b << ' ' << b.get() << ' ' << sizeof(b) << '\n';
}
$ make && ./test
g++ -Wall -Wextra -Wpedantic -Werror -Wfatal-errors  -o test test.cc
12 12 2
34 34 8