Memory layout of recursive template struct.

D

Daniel Pitts

If I have a recursive template such as:

template <typename T, unsigned size>
struct PlaceHolder {
typedef PlaceHolder<T, size-1> Next;
T value;
Next next;
PlaceHolder(const PlaceHolder &placeHolder)
: value(placeHolder.value), next(placeHolder.next) {}

PlaceHolder(const T& value, const Next &next)
: value(value), next(next) {}
};

template <typename T>
struct PlaceHolder<T, 0> {
T value;
PlaceHolder(const PlaceHolder &placeHolder) : value(placeHolder.value) {}
PlaceHolder(const T& value) : value(value) {}
};

Can I make any assumptions/assertions about the memory layout of any
particular PlaceHolder<X,Y> struct?

In particular, is the following function valid, or is it UB?

template <typename T, unsigned size>
T &get(PlaceHolder<T, size> &place, int index) {
return reinterpret_cast<T*>(&place)[index];
}
 
D

Daniel Pitts

Daniel said:
If I have a recursive template such as:

template <typename T, unsigned size>
struct PlaceHolder {
typedef PlaceHolder<T, size-1> Next;
T value;
Next next;
PlaceHolder(const PlaceHolder &placeHolder)
: value(placeHolder.value), next(placeHolder.next) {}

PlaceHolder(const T& value, const Next &next)
: value(value), next(next) {}
};

template <typename T>
struct PlaceHolder<T, 0> {
T value;
PlaceHolder(const PlaceHolder &placeHolder) :
value(placeHolder.value) {}
PlaceHolder(const T& value) : value(value) {}
};

Can I make any assumptions/assertions about the memory layout of any
particular PlaceHolder<X,Y> struct?

In particular, is the following function valid, or is it UB?

template <typename T, unsigned size>
T &get(PlaceHolder<T, size> &place, int index) {
return reinterpret_cast<T*>(&place)[index];
}

I did my own research (go figure, this information is available somewhere!)

If I replace the definitions with (including a small fix to my
off-by-one error)

template <typename T, unsigned size>
struct PlaceHolder {
T value;
PlaceHolder<T, size-1> next;
};

template <typename T>
struct PlaceHolder<T, 1> {
T value;
};

template <typename T>
struct PlaceHolder<T, 0> {
};


It appears I can even initialize it thus:
PlaceHolder<double, 3> x = {1, 2, 3};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top