C++ Class Template Example – Point and Point3D

By , last updated July 15, 2019

This is a real C++ Class Template example of a Point with different constructors that we used in our 3D game development code.

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 a 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 a main class template that is very useful in game development and 3D design: a Point class template.

Point

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. The template class has a default constructor Point(), a copy constructor to make new instances of a class and several other constructors that may take in multiple parameters.

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);
    }

Point3D

A Point3D class template will extend the Point-class template and 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 where we implement an Euler Angle rotation for 3D objects in a game:

	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.