Re: Address of first member of valarray
On 20 Apr., 04:46, Niels Dekker - no return address
<nore...@this.is.invalid> wrote:
John Moeller wrote:
I have read that if v is a std::vector, you can safely use &v[0] as
the address to contiguous memory containing the elements of the
vector.
Is the same true for std::valarray?
Daniel Kr?gler wrote:
The intend is: yes (if the valarray is not empty).
Note that the current wording of 14882:2003(E) limits this guarantee
on the non-const version of the operator[] overload, see 26.3.2.3/3:
"The expression &a[i+j] == &a[i] + j evaluates as true for all size_t i
and size_t j such that i+j is less than the length of the non-constant
array a."
because the const overload was specified to return by value.
As a workaround, I guess you can do a const_cast, if you need the
address of the contiguous buffer of a const valarray:
template <typename T> void func(const valarray<T>& va)
{
const T * data = &const_cast<valarray<T>&>(va)[0];
}
Yes, that is correct. IMO it makes sense for a programmer to add
the following helper functions (as long as there exists no data member
function in valarray):
#include <valarray>
template <typename T>
inline T* data(std::valarray<T>& va)
{
return va.size() ? &va[0] : 0;
}
template <typename T>
inline const T* data(const std::valarray<T>& va)
{
return va.size() ? &const_cast<std::valarray<T>&>(va)[0] : 0;
}
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]