C++ template operator overload for template class
An example code to perform template operator overload for a template class in C++ is provided.
Run and consider the output of the example below.
#include <iostream>
#include <vector>
using std::ostream;
using std::vector;
using std::cout;
template<class T>
class List {
private:
std::vector<T> vec;
public:
void push_back(T t){
vec.push_back(t);
};
template<class U>
friend ostream& operator<<(ostream& os, const List<U>& L );
};
template<class T>
ostream& operator<<(ostream& os, const List<T>& L ){
for (T it : L.vec){
os << it << " .. ";
}
return os;
}
int main(void){
List<int> L;
L.push_back(1);
L.push_back(2);
L.push_back(3);
std::cout << L;
return 0;
}
The expected output is:
1 .. 2 .. 3 ..
Leave a comment