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 a T&, which will work fine.
std::valarray<T>::operator [](std::size_t) const returns a T, which will be an rvalue and consequently cannot have its address taken.
Because valarray_test::pointy is itself const, valarray_test::v is treated as const and consequently the const overload of operator[] is called. Either make valarray_test::v mutable or make valarray_test::pointy non-const.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With