HP C/aC++ for PA-RISC Software manual Function Templates

Models: C/aC++ for PA-RISC Software

1 230
Download 230 pages 50.97 Kb
Page 137
Image 137

int top;

};

Class template member functions and member data use the formal parameter type, T, and the formal parameter expression, size. When you declare an instance of the class Stack, you provide an actual type and a constant expression. The object created uses that type and value in place of T and size, respectively.

For example, the following program uses the Stack class template to create a stack of 20 integers by providing the type int and the value 20 in the object declaration.

int main()

{Stack<int,20> myintstack; int i;

myintstack.push(5);

myintstack.push(56);

myintstack.push(980);

myintstack.push(1234); i = myintstack.pop();

}

The compiler automatically substitutes the parameters you specified, in this case int and 20, in place of the template formal parameters. You can create other instances of this template using other built-in types as well as user-defined types.

Function Templates

A function template defines a family of functions. To declare a function template, use the keyword template to define the formal parameters, which are types, then define the function in terms of those types. For example, the following is a function template for a swap function. It simply swaps the values of its two arguments:

template<class T>

void swap(T& val1, T& val2)

{

Ttemp=val1;

val1=val2;

val2=temp;

}

The argument types to the function template swap are not specified. Instead, the formal parameter, T, is a placeholder for the types. To use the function template to create an actual function instance (a template function), you simply call the function defined by the template and provide actual parameters. A version of the function with those parameter types is created (instantiated).

For example, the following main program calls the function swap twice, passing int parameters in the first case and float parameters in the second case. The compiler uses the swaptemplate to automatically create two versions, or instances, of swap, one that takes int parameters and one that takes float parameters.

int main()

{int i=2, j=9; swap(i,j);

float f=2.2, g=9.9; swap(f,g);

}

Other versions of swap can be created with other types to exchange the values of the given type.

Invoking Compile-Time Instantiation 137

Page 137
Image 137
HP C/aC++ for PA-RISC Software manual Function Templates