Consider the following C++ template class. #include <iostream> using namespace s
ID: 3630815 • Letter: C
Question
Consider the following C++ template class.#include <iostream>
using namespace std;
template <typename T, int length>
class SortedList
{
public:
SortedList()
{size = 0;}
void insert(T item);
friend ostream& operator<<(ostream& out, const SortedList& list)
{return list.put(out);}
private:
ostream& put(ostream& out) const;
T list[length];
int size;
};
template<typename T, int length>
void SortedList<T, length>::insert(T item)
{
if (size == length)
throw exception("List Full");
int i = size - 1;
while (i >= 0 && item < list[i])
{
list[i+1] = list[i];
i--;
}
list[i+1] = item;
size++;
}
template<typename T, int length>
ostream& SortedList<T, length>::put(ostream& out) const
{
for (int i = 0; i < size; i++)
cout << list[i] << " " ;
cout << endl;
return out;
}
int main()
{
int values[] = {5, 1, 7, 8, 11, 2};
SortedList<int, 10> list;
for (int i = 0; i < 6; i++)
list.insert(values[i]);
cout << list;
return 0;
}
The class SortedList cannot be instantiated for any arbitrary type. For example, consider the following instantiation for a wrapper integer class.
class Int
{
public:
Int(int i) {this->i = i;}
private:
int i;
};
int main()
{
Int values[] = {Int(5), Int(1), Int(7), Int(8), Int(11), Int(2)};
SortedList<Int, 10> list;
for (int i = 0; i < 6; i++)
list.insert(values[i]);
cout << list;
return 0;
}
Explain why the second implementation fails. What must be added to that class so this program will compile? Suppose this program were written in Java. Explain how Java allows the constraints on a generic type parameter to be specified and how they would be specified in this case
Java does have one limitation, however. Although wrapper classes can be used to instantiate generic type parameters, primitive types cannot. Explain why.
Explanation / Answer
The problem with the Int class is that it doesn't implement the stream operator (Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.