![](/style/images/good.png)
![](/style/images/bad.png)
C++ template operator overload for template class
source link: https://adaickalavan.github.io/cpp/template-operator-overload/#gsc.tab=0
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
C++ template operator overload for template class
less than 1 minute read
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 ..
Tags: template
Categories: cpp
Updated: December 27, 2020
Previous NextRecommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK