I’m trying to extract a const pointer to part way through an array. I found it works fine when using a vector, but won’t compile (VS 2008) when using a valarray. Can somebody explain what the problem is?
struct vector_test
{
std::vector<int> v;
const int *pointy(const int i) const
{
return &(v[i]); // Ok
}
};
struct valarray_test
{
std::valarray<int> v;
const int *pointy(const int i) const
{
return &(v[i]); // error C2102: '&' requires l-value
}
};
std::valarray<T>::operator [](std::size_t)returns aT&, which will work fine.std::valarray<T>::operator [](std::size_t) constreturns aT, which will be an rvalue and consequently cannot have its address taken.Because
valarray_test::pointyis itselfconst,valarray_test::vis treated asconstand consequently theconstoverload ofoperator[]is called. Either makevalarray_test::vmutableor makevalarray_test::pointynon-const.