Witam , mam problem z dziwnym zachowaniem kompilatora podczas przeciążania operatora << w poniższej klasie:
#ifndef VECTORS_H
#define VECTORS_H
#include <iostream>
#include <vector>
namespace enbr { // <---
template<class T>
class AnyVector {
public:
AnyVector(const std::initializer_list<T>&);// zapewniony
~AnyVector(); //zapewniony
private:
unsigned int size;
std::vector<T> element;
public:
template<class U>
friend std::ostream& operator<< (std::ostream&,const enbr::AnyVector<U>&);
};
} // <---
template<class U>
std::ostream& operator<< (std::ostream& os,const enbr::AnyVector<U>& vec){
for(unsigned int i = 0;i< vec.get_size();i++)// zapewniłem funkcję get_size()
os << vec.element[i] << " ";
return os;
}
#endif // VECTORS_H
W tym przypadku wyskakuje błąd :
main.cpp / błąd: use of overloaded operator '<<' is ambiguous (with operand types 'std::ostream' (aka 'basic_ostream<char>') and 'enbr::AnyVector<double>')
main.cpp: błąd: ambiguous overload for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘enbr::AnyVector<double>’)
std::cout << v1;
Ale ,gdy zasięgiem przestrzeni nazw embr obejmę również definicję operatora << , to problem znika. Dlaczego ?
#ifndef VECTORS_H
#define VECTORS_H
#include <iostream>
#include <vector>
namespace enbr { // <---
template<class T>
class AnyVector {
public:
AnyVector(const std::initializer_list<T>&);// zapewniony
~AnyVector(); //zapewniony
private:
unsigned int size;
std::vector<T> element;
public:
template<class U>
friend std::ostream& operator<< (std::ostream&,const enbr::AnyVector<U>&);
};
template<class U>
std::ostream& operator<< (std::ostream& os,const enbr::AnyVector<U>& vec){
for(unsigned int i = 0;i< vec.get_size();i++)// zapewniłem funkcję get_size()
os << vec.element[i] << " ";
return os;
}
} // <---
#endif // VECTORS_H
main.cpp
#include "vectors.h"
#include <iostream>
int main(){
enbr::AnyVector<double> v1{3.0,3.0,4.0};
std::cout << v1;
return 0;
}