I am following an example in section 7.2 of A Tour of C++ where I have a class which I want to iterate over in a range-for loop.
First, I have the parent.
template<typename T>
class Container {
public:
virtual T& operator[](int i) const = 0;
virtual int size() const = 0;
virtual ~Container() {}
};
Second, I define the class itself. I define begin and end in order to iterate over the class in a range-for loop.
template<typename T>
class MyVector: public Container<T> {
public:
explicit MyVector(int s);
MyVector(std::initializer_list<double>);
T& operator[](int i) const override {
if (i<0 || i>size()) throw std::out_of_range{"Anatoly's Vector operator []"};
return elem[i];
}
auto begin(MyVector<T>& x) -> T* const {return &x[0];}
auto end(MyVector<T>& x) -> T* const {return &x[0] + x.size();}
protected:
T* elem;
int sz;
Define the constructors:
template<typename T>
MyVector<T>::MyVector(int s)
:elem{new T[s]}, sz{s} // initialize members
{
std::cout << "Default constructor called" << std::endl;
}
template<typename T>
MyVector<T>::MyVector(std::initializer_list<double> lst) // initialize with a list
:elem{new T[lst.size()]}, sz{static_cast<int>(lst.size())}
{
std::copy(lst.begin(),lst.end(),elem);
}
template<typename T>
auto MyVector<T>::size() const -> int {
return sz;
};
Finally, this is how I intend to use it:
void write2(MyVector<std::string>& vs) // Vector of some strings
{
for (auto& s: vs)
std::cout << s << '\n';
}
But this doesn't compile. I get this compiler error:
In function 'void write2(MyVector<std::__cxx11::basic_string<char> >&)':
no matching function for call to 'MyVector<std::__cxx11::basic_string<char> >::begin()'
for (auto& s: vs)
note: candidate: 'T* MyVector<T>::begin(MyVector<T>&) [with T = std::__cxx11::basic_string<char>]'
candidate expects 1 argument, 0 provided
What am I doing wrong? Why candidate expects 1 argument, but 0 provided? How do I fix this?
EDIT:
As commentators kindly suggested, begin should not take arguments, which explains the error message. I have misinterpreted the book, where begin is defined outside of the class:
