C++ cast raw table to another table type

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

I want to write class similar to the std::array from C++11. To do this I am declaring a table of type char inside this class and later I would like to call placement new on this table After that I would like to use table as if it was regular table of type T and here comes the trouble.

Generally variable like:

char tab[size];  

Is of type char(&)[size] and if that's so I would like to use reinterpret_cast on this table to cast it to table of type, that I am in fact using, so more or less I would like my code to look like this:

char tab[sizeof(T)*size]; T tabT[size] = reinterpret_cast<T(&)[size]>(tab); // more code using tabT 

However in this context tab is seen as char* type. Reason, why I thought it could work is ability to write following template function

template <typename T, size_t size> function(T(&table)[size]){     //do stuff connected with table of type T and size size. } 

I know I could do this without this fancy magic here, but I just want to know, why it does not work.

So my question is: Is there a way to do the thing I want to do and is there any more elegant way to do mentioned job?

PS: I do not declare raw table of type T like : T tab[size], because I wouldn't be able to create elements, where there is no constructor without arguments.

回答1:

The cast doesn't really help you:

char tab[sizeof(T)*size]; T tabT[size] = reinterpret_cast<T(&)[size]>(tab); 

Since arrays aren't copyable this code doesn't compile when instantiated. At the very least you'd need to use

T (&tabT)[size] = reinterpret_cast<T(&)[Size]>(tab); 

However, I'd recommend not to store the uninitialized elements as char array to start with. Just use a union with a nested array:

template <typename T, int Size> class array {     union Data {         Data() {}         T values[Size];     } data; public:     array() { /* initialize the elements appropriately */ }     ~array() { /* destroy the initialized elements */ }     // ... }; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!