I can’t understand why the following code is not working, any idea ?
template <class T>
class Matrice
{
public:
...
typedef typename std::vector<T>::const_iterator const_iterator;
const_iterator& cend ( )
{
return valeurs.cend ( );
}
...
private:
...
}
here’s the complilator’s complaint :
/Users/Aleks/Documents/DS OO/DS OO/Matrice.h:70:16: Non-const lvalue
reference to type ‘const_iterator’ (aka ‘__wrap_iter’)
cannot bind to a temporary of type ‘const_iterator’ (aka
‘__wrap_iter’)
valeurs.cend(cppreference) returns an instance to aconst_iterator(that is, it’s declared asconst_iterator valeurs.cend()).The compiler needs to create a temporary object (memory area) to store the value returned by
valeurs.cend(). This code fails to compile because you cannot take the reference of a temporary as the latter won’t outlive the function call.You’d usually return an iterator by value:
This will make sure the value returned by
valeurs.cend()is copied (or moved, in C++11, I believe) to its the destination object (if you’re assigning the returned value to a variable of typeconst_iterator) or in another temporary whereverMatrice<T>::cend()is called. See the link to MSDN’s explanation for details.