Witam !
Chciałbym żeby obiekt utworzony z klasy wektor można było użyć w pętli for bez definiowania operatora []
template<typename T>
class Vector {
private:
T*elem;
int sz;
public:
Vector(int s);
~Vector() { delete[] elem; }
T& operator[](int i);
const T& operator[](int i) const;
int size() const { return sz; }
};
template<typename T>
Vector<T>::Vector(int s)
{
elem = new T[s];
sz = s;
}
template<typename T>
const T& Vector<T>::operator[](int i) const
{
if (i<0 || size()<=i)
throw out_of_range{"Vector::operator[]"};
return elem[i];
}
template<typename T>
T*begin(Vector<T>& x)
{
return &x[0];
}
template<typename T>
T*end(Vector<T>& x)
{
return x.begin()+x.size();
}
void f2(const Vector<string>& vs)
{
for (auto& s : vs)
cout << s << '\n';
}
Przy próbie kompilacji otrzymuje :
error: no matching function for call to 'begin(const Vector<std::__cxx11::basic_string<char> >&)'
for (auto& s : vs)
test.cpp:39:3: note: candidate: template<class T> T* begin(Vector<T>&)
T*begin(Vector<T>& x)
^~~~~
test.cpp:39:3: note: template argument deduction/substitution failed:
test.cpp:52:20: note: types 'Vector<T>' and 'const Vector<std::__cxx11::basic_string<char> >' have incompatible cv-qualifiers
for (auto& s : vs)
Co robię źle ?