Templates
- What is the output of this program?
#include <iostream>
using namespace std;
template <class T, int Num>
class Sequence
{
T memblock [Num];
public:
void setMember (int x, T value);
T getMember (int x);
};
template <class T, int Num>
void Sequence<T,Num> :: setMember (int x, T value)
{
memblock[x] = value;
}
template <class T, int Num>
T Sequence<T,Num> :: getMember (int x)
{
return memblock[x];
}
int main ()
{
Sequence <int, 4> myints;
Sequence <double, 4> myfloats;
myints.setMember (0, 150);
myfloats.setMember (3, 4.125);
cout << myints.getMember(0) << '\n';
cout << myfloats.getMember(3) << '\n';
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
In this program, We are printing the integer in the first function and float in the second function.
- What is the output of this program?
#include <iostream>
using namespace std;
template<typename T>
void loopIt(T p)
{
int n = 2;
T val[n];
for (int k=0; k < n; k++)
{
val[k] = p++;
cout << val[k] << endl;
}
};
int main()
{
float q = 4.25;
loopIt(q);
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: B
In this program, We are using the for loop to increment the value by 1 in the function template.
- What is the output of this program?
#include <iostream>
using namespace std;
template<typename T>
inline T square(T num1)
{
T Res;
Res = num1 * num1;
return Res;
};
int main()
{
int k, kk;
float num1, num2;
double num3, num4;
k = 3;
num1 = 2.3;
num3 = 4.2;
kk = square(k);
cout << k << " " << kk << endl;
num4 = square(num3);
cout << num3 << " " << num4 << endl;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
In this program, We are passing the values and calculating the square of the value by using the function template.
- What is the output of this program?
#include <iostream>
using namespace std;
template<typename type>
class Test
{
public:
virtual type Function(type num1)
{
return num1 * 2;
}
};
int main()
{
Test<int> num1;
cout << num1.Function(150) << endl;
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
In this program, We are using class to pass the value and then we are manipulating it.