Buen día, estoy tratando de sobrecargar el operador << en una plantilla. Lo he probado con los tipos int, double, etc. y funciona bien, pero con strings falla.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template<typename T> inline vector<T> &operator<<(vector<T> &v, const T &val){
v.push_back(val);
return v;
}
int main(){
vector<string> strs;
strs << "w1" << "w2" << "w3" << "w4";
vector<string>::iterator i;
for(i = strs.begin(); i < strs.end(); i++)
cout << *i << " ";
return 0;
}
Este es el error que pone:
main.cpp:14: error: no match for 'operator<<' (operand types are 'std::vector<std::__cxx11::basic_string<char> >' and 'const char [3]')
main.cpp: In function 'int main()':
main.cpp:14:10: error: no match for 'operator<<'
(operand types are 'std::vector<std::__cxx11::basic_string<char> >' and 'const char [3]')
14 | strs << "wi" << "w2" << "w3" << "w4";
| ~~~~ ^~ ~~~~
| | |
| | const char [3]
| std::vector<std::__cxx11::basic_string<char> >
note: candidate: 'template<class T> std::vector<T>& operator<<(std::vector<T>&, const T&)'
7 | template<typename T> inline vector<T> &operator<<(vector<T> &v, const T &val){
| ^~~~~~~~
main.cpp:7:40: note: template argument deduction/substitution failed:
main.cpp:14:13: note: deduced conflicting types for parameter 'const T' ('std::__cxx11::basic_string<char>' and 'char [3]')
14 | strs << "wi" << "w2" << "w3" << "w4";
| ^~~~