Class templates in C++

By , last updated June 8, 2017

Templates in C++ are the way functions and classes operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one [wiki].

Note that there is a difference between class template and a template class: class template is a template used to generate template classes. You cannot declare an object of a class template. Template class is an instance of a class template.

Here we are going to look at 3 main class templates that are very useful in game and 3D design: Point, Vector and Matrix class templates.

Point and Point3D:

Here is how a simple Point template will look like in C++. This template is constructed to support multiple dimensions like Point2D, 3D and so on:

template <class T, int n> class Point {
protected:
	T mat[n];
	 void cp(const Point<T,n> &p)
    {
		memcpy(mat, p.mat, n*sizeof(T) );
	 }

    void cp(const T p[n])
    {
		memcpy(mat, p, n*sizeof(T) );
	}

    void cp(const T &val)
    {
		for (int i=0; i<n; i++)
			mat[i] = val;
    }

public:
	// new constructor
	Point(const T pt[n])
	{
		cp(pt);
	}

	// copy constructor
	Point(const Point<T,n> &cp)
	{
		this->cp(cp);
	}

	// default constructor
	Point()
	{
		for (int i=0; i<n; i++)
			mat[i] = 0;
	}
	virtual ~Point(void) {};
};

Templates are of great utility to programmers in C++, especially when combined with multiple inheritance and operator overloading. Here vi can add multiple operator overloading functions to our Point class template, for example addition:

        //Point + some value
	Point<T,n> &operator+=(const T &val)
    {
		for (int i=0; i<n; i++)
			mat[i] += val;

		return (*this);
    }

    //sum of two Points
    Point<T,n> &operator+=(Point<T,n> &pt)
    {
		for (int i=0; i<n; i++)
			mat[i] += pt[i];

		return (*this);
    }

A Point3D class template will look like this:

template <class T> class Point3D : public Point<T,3> {
public:
	Point3D() : Point<T,3>() {};

	Point3D(const Point3D<T> &p) : Point<T,3>(p) {
		for (int i=0; i<3; i++)
		mat[i] = p.mat[i];
	}
	Point3D( const T px, const T py, const T pz)
	{
		mat[0]=px; mat[1]=py; mat[2]=pz;
	}
};

An example of how we can use it is a motion programming:

	Point3D<float> EulerAngle(float sensitivity, double x, double y, double z) {
		return Point3D<float> (
				sensitivity*cos(z),
				sensitivity*sin(z),
				0
		);
	}

Senior Software Engineer developing all kinds of stuff.

Comments

Be the first to comment.

Leave a Reply


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*