Thursday, 18 June 2015

Template Arguments versus Template Parameters

Template Arguments versus Template Parameters

In this post I would like to clarify what is the difference between the template arguments and template parameters. Here is the sample syntax
template <Type T, int iIndex>

class ArrayInClass {


    T TempArrayObj[iIndex];


The below is the sample plain class.

class DoubleMyArrary {


    double TempArrayObj[10];


It is essential to distinguish between template parameters and template arguments. In real world arguments are called as actual parameters and the parameters are called as formal parameters.
Template parameters: The template parameter names are listed after the keyword template in the template declaration.

Template arguments: The template arguments are the items that are substituted for template parameters

The substitution of template parameters by template arguments is explicit when indicated with a template-id, but there are various situations when the substitution is implicit (for example, if template parameters are substituted by their default arguments).

A fundamental principle is that any template argument must be a quantity or value that can be determined at compile time.

As becomes clear later, this requirement translates into dramatic benefits for the run-time costs of template entities. Because template parameters are eventually substituted by compile-time values, they can themselves be used to form compile-time expressions. This was exploited in the MyArrary template to size the member TempArrayObj TempArrayObj. The size of a TempArrayObj must be a so-called constant-expression, and the template parameter N qualifies as such.

The latter becomes essentially equivalent to the former if we replace the parameters T and iIndex by double and 10 respectively.
In C++, we can replace the above statement as shown below.Here the arguments are declared in the angular brackers

Template-Id means that the combination of the template name, followed by the arguments in angle brackets.
See the below example
int main()


    MyArrary<double,10> Arra;

    Arra.TempArrayObj[0] = 1.0;


The template parameters are compile-time entities and these can be used to create valid template arguments.
Let us see the sample name Temp is both a template parameter and a template argument.

template <Type T>

class Example {
    MyArrary<Temp,12> contents;

No comments: