I am trying to modify the class “cpair” and the function “Add” to be a template class and function.
#include "stdafx.h"
#include <iostream>
using namespace std;
class cpair
{
public:
cpair(int x=0, int y=0) {A=x; B=y;}
void print()
{cout << A <<" "<<B<<endl;}
int A, B;
};
void Add(cpair A1, cpair A2, cpair &R)
{
R.A= A1.A + A2.A;
R.B= A1.B + A2.B;
}
int _tmain(int argc, _TCHAR* argv[])
{
cpair A1(4,5), A2(1,3), result;
Add(A1, A2, result);
result.print();
return 0;
}
This is my implementation below, but I have an error C2146: syntax error : missing ',' before identifier 'A1'.
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
using namespace std;
template <class T>
class cpair
{
public:
cpair(T x=0, T y=0) {A=x; B=y;}
void print()
{cout << A <<" "<<B<<endl;}
T A, B;
};
template <class T>
void Add(T cpair A1, T cpair A2, T cpair &R)
{
R.A= A1.A + A2.A;
R.B= A1.B + A2.B;
}
template <class T>
int _tmain(int argc, _TCHAR* argv[])
{
cpair A1(4,5), A2(1,3), result;
Add(A1, A2, result);
result.print();
return 0;
}
How do I convert the class and function to be a template class and function?