Devs.site

Starting with classes, functions and variables templates in C++

In this brief article for beginners we will make first contact with a modern feature of C++ that within the object-oriented aspect of this language proves itself essential when it comes to creating reusable, extensible and compact code at the same time. Templates have been consolidated in the C++11 version and have been extended through following releases of the language. C++14 added variable templates and relaxes several restrictions.


Many languages, including C++, need you to explicitly specify what the type of a variable is. You cannot just say:

height = 80;

and expect the compiler to know that height is a number, even if for us it is obvious. You need to specify the type of it:

int height = 80; // this is an integer

Compilers or interpreters of generic programming languages can figure that out from the value, although most of them also allow you to clearly state their type.

C++ doesn't have that but it has another powerful utility for those who need to write type independent code in a reliable way. With templates you can cover the handling of any type of variable declaration or function return and its arguments. You can also create classes that behave accordingly to each type of data you hand them.

Variable templates

In the example above we saw that we need to inform the compiler about the type of a declared variable. What if we need the same height variable to be used as different types? Normally, we would declare the same variable for each type that we need in our calculations.

int int_height = 180;
double double_height = 5.10;
char str_height[] = "tall";

By using a template, we can instantiate the variable for each type. First, we declare the template

template<typename T>
T height = T(0);

and then we assign it whatever value we want. We don't need 3 variables. The compiler will know which value to pick.

height<int> = 180;
height<double> = 5.11;
height<const char*> = "tall";

std::cout << height<int>;
std::cout << height<double>;
std::cout << height<const char*>;
std::cout << height<bool>;

The output will be:

180
5.11
tall
0

We have not assigned a value for the bool type, so the one defined in the template is returned. Templated variables are not a big deal by themselves, so we will proceed with the next, more practical case.

Functions templates

Templated functions can receive arguments of generic types and also return a result of generic type. The following code will calculate the normal body weight for both centimeters and inches. First, we have the function template and secondly we have a specialization of the template for the double type (used for values of imperial units)

template <typename T>
T nbw(T h)
{
    return h - 100;
}

template <>
double nbw<double>(double h)
{
    return ((int)h * 30.48 + ((double)h - (int)h) * 100 * 2.54) - 100;
}

std::cout << nbw(height<int>);
std::cout << nbw(height<double>);
Class templates

Based on the same concept, we also have classes that can work with template parameters as types for their members. And just like with function and variables, they can me specialized for a certain type.

template <class T>
class person {
    T height = T(0);
public:
    person(T h)
    {
        height = h;
    }

    T nbw() {
        T nw;
        nw = this->height - 100;
        return nw;
    }
};

template <>
class person <double> {
    double height;
public:
    person(double h) {
        height = h;
    }
    double nbw()
    {
        double nw;
        nw = ((int)this->height * 30.48 + ((double)this->height - (int)this->height) * 100 * 2.54) - 100;
        return nw;
    }
};

float preciseHeight = 180.24f;

person me(preciseHeight);
std::cout << me.nbw();

person<int> you(height<int>);
std::cout << you.nbw();

person<double> him(height<double>);
std::cout << him.nbw();

One single class handles floats, integers and doubles to do the same task. We don't need to triplicate the same code for each type. This is the main power of templates as a programming model. Obviously, in this examples it seems we could use other options and templates are not necessary. But we will see more complex cases where templates show their mettle. For now, you have been shown the syntax and examples of their basic use.

0 comments

Specify your e-mail if you want to receive notifications about new comments and replies