I'm writing array wrapper in C++ (like std::array
). The motivation was to make array-wrapper a derivative of interface. This enables to pass arrays to functions without making them templated (through interface). The way of implementing it is a little suspicious-looking so I want to ask if the code below is legal in C++ or not?
The example shows the way of using union members, I tried to make the smallest example so Interface and other stuff is not present here. Main problem is union member usage in that way. The reason I do so it to make possible to create array of types with no default c-tor (Unfortunately, this example doesn't show this too).
template<typename T, size_t N>
class Array
{
public:
Array() :
m_data( m_originalObjects ),
m_len(N),
m_place()
{
for( decltype(N) i = 0; i < N; i++ )
{
new( &m_data[i] )T();
}
}
//c-tor to objects without default c-tor
template<typename ... TCon>
Array( TCon && ... values ) :
m_data( m_originalObjects ),
m_len(N),
m_originalObjects{ static_cast<T>(values)... }
{
}
private:
T * m_data = nullptr;
size_t m_len = 0;
union
{
char m_place[sizeof(T) * N];
T m_originalObjects[N];
};
};