CS 330 Lecture 24 – Templates

Agenda

  • what ?s
  • program this
  • a templated vector class
  • overloading builtin operators

TODO

Program This

A vector is a quantity in n-dimensions. 2-D vectors can represent points in 2-D space or offsets in 2-D space. 3-D vectors do the same in 3-D. And so on. Consider an operation/method that one might perform on a vector. Write pseudocode to perform the operation.

Code

QVector.h

#ifndef QVECTOR_H
#define QVECTOR_H

#include <cassert>
#include <cmath>
#include <iostream>

using std::ostream;

template <typename T, int ndims>
class QVector {
  public:
    /* QVector() { */
    /* } */

    QVector(T fill = 0) {
      for (int i = 0; i < ndims; ++i) {
        coords[i] = fill;
      }
    }

    T operator[](int i) const {
      assert(i >= 0 && i < ndims);
      return coords[i];
    }

    T& operator[](int i) {
      assert(i >= 0 && i < ndims);
      return coords[i];
    }

    QVector<T, ndims> operator+(const QVector<T, ndims>& other) {
      QVector<T, ndims> sum;
      for (int i = 0; i < ndims; ++i) {
        sum[i] = coords[i] + other[i];
      }
      return sum;
    }

    T GetMagnitude() const {
      T sum = 0;
      for (int i = 0; i < ndims; ++i) {
        sum += coords[i] * coords[i];
      }
      return sqrt(sum);
    }

  private:
    T coords[ndims];
};

template <typename T, int ndims>
ostream& operator<<(ostream& out, const QVector<T, ndims>& v) {
  for (int i = 0; i < ndims; ++i) {
    out << v[i] << " ";
  }
  out << std::endl;
  return out;
}

#endif

vector_test.cpp

#include <iostream>
#include "QVector.h"

int main(int argc, char **argv) {
  QVector<int, 4> v1;
  std::cout << "v1: " << v1 << std::endl;
  std::cout << "v1[0]: " << v1[0] << std::endl;
  std::cout << "v1[1]: " << v1[1] << std::endl;
  std::cout << "v1[2]: " << v1[2] << std::endl;
  std::cout << "v1[3]: " << v1[3] << std::endl;
  v1[0] = 7;
  std::cout << "v1[0]: " << v1[0] << std::endl;
  std::cout << "v1[1]: " << v1[1] << std::endl;
  std::cout << "v1[2]: " << v1[2] << std::endl;
  std::cout << "v1[3]: " << v1[3] << std::endl;
  std::cout << "v1: " << v1 << std::endl;
  v1 = v1 + v1;
  std::cout << "v1: " << v1 << std::endl;
  std::cout << "v1.GetMagnitude(): " << v1.GetMagnitude() << std::endl;
  /* QVector<double, 3> v2; */
  /* QVector<bool, 2> v3; */
  return 0;
}

Haiku

It started with New York
Now you can ♥ anything
‘Cuz they are <T>-shirts

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *