Simple function and template question

Hi,
Can somebody explain the line below.. Especially the &d part
 
 void copyFrom(const DateClass &d) 


and (template)

 
k = sum<int> (i,j);

Please explain the <int> part, what is the function of having it there?
void copyFrom(const DateClass &d)
Usually C++ passes function parameters to the function by value. That means that it makes a copy of whatever the caller passes in. Thus if the function modifies the parameter, it won't have any effect on the caller's argument, only on the local copy.

When you add the &, it tells the compiler that you're passing by reference. The function receives a reference to the caller's argument. In your case notice that it's a const reference. That means the compiler will complain if the function tries to modify the parameter. Passing parameters by const reference is a handy way to avoid the cost of making a copy of an argument that's a class instance where it might be expensive to make a copy.

k = sum<int> (i,j);
Instantiate the sum<int> and call it. You might do this to ensure that sum<> is instantiated with the type that you intend.
@OP, below is just a simplified version of the use of template.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <iomanip> //To use fixed, showpoint, and setprecision.

template <class T>
T div(T, T);

int main()
{
	float num1{ 10 }, num2{ 4 };
	std::cout << std::fixed << std::showpoint << std::setprecision(2);
	std::cout << "The answer of div<int>(10, 4) (10 / 4): " << div<int>(num1, num2) << std::endl;
	std::cout << "The answer of div<float>(10, 4) (10 / 4): " << div<float>(num1, num2) << std::endl;

	return 0;
}

template<class T>
T div(T num1, T num2)
{
	return T(num1 / num2);
}


The output:
The answer of div<int>(10, 4) (10 / 4): 2
The answer of div<float>(10, 4) (10 / 4): 2.50
Last edited on
Topic archived. No new replies allowed.