0

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";
      |             ^~~~

1 respuesta 1

1

El operador está correctamente sobrecargado. Lo que sucede es que los literales de cadenas son de tipo const char * o const char[] como te indica el compilador.

Puedes crear strings temporales con el propósito de satisfacer la sobrecarga:

strs << string("w1") << string("w2")<< string("w3") << string("w4");

O usar un literal de la librería string, agregando una s luego de cerrar las comillas:

strs << "w1"s << "w2"s << "w3"s << "w4"s;

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.