Suppose I have a class with two array members, of the same element type but different sizes:
struct X
{
string a[2];
string b[3];
};
constexpr auto array_members = std::array{ &X::a, &X::b };
This does not compile, because the two arrays (having different lengths) have incompatible types.
Is there a common type to which both member pointers can be assigned?
I have also tried static_cast<string (X::*)[]>(&X::a)
but this also does not compile because of the incomplete array type.
I cannot use offsetof
because it needs to work with non-standard-layout classes.
This may be a workaround:
using array_type = decltype(X::b);
auto const array_members = std::array{
reinterpret_cast<array_type X::*>(&X::a), // cannot be constexpr
&X::b
};
but I am concerned about invoking undefined behavior. Although I am confident that there are no out-of-bounds element references at run-time, we do create one-past-the-end pointers to a
, which given the type of b
appear to be in-bounds. I am not sure whether this goes against the spec. Also it would be convenient if I could use constexpr
which is incompatible with reinterpret_cast
.