Home

Function Templates

 

Introduction

In previous programs, we found out that we could pass any type of value, based on one of the primitive data types, to the WriteLine() method of the Console class and it would appropriately display the value. Here are examples:

using namespace System;

// Display the value of an integer
void Show(int value)
{
    Console::WriteLine(value);
}

// Display the value of a double-precesion value
void Show(double value)
{
    Console::WriteLine(value);
}

// Display the value of a character
void Show(__wchar_t value)
{
    Console::WriteLine(value);
}

int main()
{
    // Call the version of the function that displays an integer
    Show(246);
    // Call the version of the function that displays a character
    Show('G');
    // Call the version of the function that displays a decimal
    Show(355.65);

    return 0;
}

This would produce:

246
G
355.65
Press any key to continue . . .

We passed a constant value directly to the function when we called it. Remember that you can also first declare a variable, assign it a value, and then pass that variable to the function. Here are examples:

int main()
{
    // Call the version of the function that displays an integer
    int Value1 = 246;
    Show(Value1);
    // Call the version of the function that displays a character
    __wchar_t Value2 = L'G';
    Show(Value2);
    // Call the version of the function that displays a decimal
    double Value3 = 355.65;
    Show(Value3);

    return 0;
}

Although this is based on the concept of function overloading, another way you can solve this type of problem is to create one function that doesn't know the type of value that would be passed to it but the function is equipped to process the value appropriately. Based on the above program, you can create one function that takes an argument and it displays its value. To do this, at the time you are defining the function, you only let it know that it would receive an argument but you don't specify the type of value that it will process. This the basis of templates in C++.

Practical LearningPractical Learning: Introducing Templates

  1. Start Microsoft Visual C++ if necessary.
    To create a new program, on the Start Page, click the Project button on the right side of Create
  2. In the Templates list, click Win32 Console Application
  3. Set the name to CommercialStore1
  4. Click Next
  5. Click Empty Project and click Finish
  6. On the main menu, click Project -> Add New Item
  7. In the Templates list, click C++ File (.cpp)
  8. Set the name of the file to Exercise and press Enter
  9. Complete the file as follows:
     
    #include <iostream>
    using namespace std;
    
    typedef double ItemType;
    
    struct CItem
    {
        ItemType Item;
        CItem *Next;
    };
    
    CItem * Head = NULL;
    int Size;
    
    int Count()
    {
        return Size;
    }
    
    int Add(CItem * NewItem)
    {
        CItem * Sample = new CItem;
    
        Sample          = NewItem;
        Sample->Next    = Head;
        Head            = Sample;
        
        return Size++;
    }
    CItem * Retrieve(int Position)
    {
        CItem * Current = Head;
    	
        for(int i = Count() - 1; i > Position && Current != NULL; i--)
        {
            Current = Current->Next;
        }
    
        return Current;
    }
    
    void ShowItem(ItemType item)
    {
        cout << "Item: " << item << endl;
    }
    
    int main()
    {
        CItem * Part;
    
        Part  = new CItem;
        Part->Item = 97.43;
        Add(Part);
    	
        Part  = new CItem;
        Part->Item = 274.87;
        Add(Part);
    
        Part  = new CItem;
        Part->Item = 8.7873;
        Add(Part);
    
        Part  = new CItem;
        Part->Item = 2764.4;
        Add(Part);
    
        Part  = new CItem;
        Part->Item = 92.4662;
        Add(Part);
    
        Part  = new CItem;
        Part->Item = 66800.85;
        Add(Part);
    
        cout << "-=- List of Items -=-" << endl;
    
        for(int i = 0; i < Count(); i++)
        {
            CItem * One = Retrieve(i);
    
            ShowItem(One->Item);
        }
    
        cout << "\nNumber of Items: " << Count() << "\n\n";
    
        return 0;
    }
  10. Exercise the application to see the result
     
    -=- List of Items -=-
    Item: 97.43
    Item: 274.87
    Item: 8.7873
    Item: 2764.4
    Item: 92.4662
    Item: 66800.9
    
    Number of Items: 6
    
    Press any key to continue . . .
  11. Close the DOS window

Template Function Creation

A template function is a function that can process a value whose type is known only when the variable is accessed. To create a function template, use the following formula:

template <class Parameter> ReturnType FunctionName(Argument(s)) { }

The template keyword, the class keyword, the <, and the > operators are required. On the right side of the class keyword, type a name that follows the rules of names in C++. Most programmers simply use the letter T. In our example, we use the Parameter name. After that, define the function as we have done so far. Here is an example:

template <class TypeOfValue>
void Show()
{
}

In our lesson and in the examples, the Parameter factor will be referred to as template parameter or parameter type and sometimes simply as parameter.

Passing the Template Parameter as Argument

To indicate that the function will process a value that is based on the parameter, that is, the type on the right side of the class keyword, you should pass it as argument to the function. You do this by preceding the name of the argument with the Parameter factor. Here is an example:

template <class TypeOfValue>
void Show(TypeOfValue Argument)
{
}

 In the body of the function, you can then process the Parameter as you see fit. At a minimum, and based on our earlier program, you can simply display the value by passing it to the Console::WriteLine() method. Here is an example:

template <class TypeOfValue>
void Show(TypeOfValue value)
{
    Console::WriteLine(value);
}

Practical LearningPractical Learning: Creating a Function Template

  1. To create a function template, change the ShowItem() function as follows:
     
    template <class T>
    void ShowItem(T item)
    {
        cout << "Item: " << item << endl;
    }
  2. Execute the application and notice that it works fine

Calling a Function Template

As mentioned earlier, one of the particularities of a function template is that, at the time it is defined, the function doesn't know the type of the parameter. This means that, when calling the function, you must make sure you clearly specify the type of value that will be processed. You can do this by directly passing (a constant of) the type of value that the function will process. Here are different examples of calling our Show() function:

using namespace System;

template <class TypeOfValue>
void Show(TypeOfValue value)
{
    Console::WriteLine(value);
}

int main()
{
    // Call the function and pass it an integer value
    Show(246);
    // Call the function and pass it a character value
    Show(L'G');
    // Call the function and pass it a double-precision value
    Show(355.65);

    return 0;
}

When complied and executed, this program would produce:

246
71
355.65
Press any key to continue . . .

As an alternative, you can type the name of the function, followed by angle brackets. Inside of the brackets, enter the data type of the value that will be processed. After the angle brackets, open the parentheses and, inside of them, type the constant value that will be processed. Here are examples:

using namespace System;

template <class TypeOfValue>
void Show(TypeOfValue value)
{
    Console::WriteLine(value);
}

int main()
{
    // Call the function and pass it an integer value
    Show<int>(246);
    // Call the function and pass it a character value
    Show<__wchar_t>(L'G');
    // Call the function and pass it a double-precision value
    Show<double>(355.65);

    return 0;
}

Remember that you can also first declare a variable, assign it a value, and then pass that variable to the parentheses of the function. Here are examples:

using namespace System;

template <class TypeOfValue>
void Show(TypeOfValue &value)
{
    Console::WriteLine(value);
}

int main()
{
    // Call the function and pass it an integer value
    int a = 246;
    Show<int>(a);

    // Call the function and pass it a character value
    __wchar_t  u = L'G';
    Show<__wchar_t>(u);

    // Call the function and pass it a double-precision value
    double  x = 355.65;
    Show<double>(x);

    return 0;
}

You can also declare the value as a constant before passing it to the function.

 

Previous Copyright © 2006-2016, FunctionX, Inc. Next