Re: Is there a portable way to use pointer arithmetics with members.
Am 27.11.2010 20:15, schrieb Elias Salom?o Helou Neto:
Hi,
Suppose I have the following class template:
template< unsigned n, class T>
class npoint {
T head_;
npoint< n - 1, T> tail_;
public:
T& get( unsigned i ) // Works with GCC 4.5
{
return( *(&head_ + i ) );
}
};
template< class T>
class npoint< 0u, T> {};
My question is whether the get() member function is guaranteed to
work.
This is not guaranteed to work. The standard only guarantees for some special types (standard-layout structs) that a pointer to the structure can be reinterpreted as the pointer to the first initial member and vice versa. But 9.2/21 emphasizes in a note that this rule does not extend to the second or further members:
"[ Note: There might therefore be unnamed padding within a standard-layout struct object, but not at its beginning, as necessary to achieve appropriate alignment. ?end note ]"
If not, is there a portable way of accessing elements of an
object of such a class?
Yes, by making get a recursive function:
template< unsigned n, class T >
class npoint {
template<unsigned, class> friend class npoint;
T head_;
npoint< n - 1, T > tail_;
public:
T& get(unsigned i)
{
return i == 0 ? head_ : tail_.get(i - 1);
}
};
template< class T >
class npoint<0, T> {
template<unsigned, class> friend class npoint;
T& get( unsigned i ) {
... // Some error situation
}
};
HTH & 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! ]