且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++将原始表转换为另一个表类型

更新时间:2023-01-07 15:11:25

不真正帮助你:

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

由于数组不可复制,所以代码实例化时不会编译。至少你需要使用

  T(& tabT)[size] = reinterpret_cast< T(& )[Size]>(tab);但是,我建议不要将未初始化的元素存储为 char  $ p> 

数组开始。只需使用嵌套数组使用 union
  template< typename T,int Size> 
类数组
{
联合数据{
数据(){}
T值[大小];
} data;
public:
array(){/ *适当初始化元素* /}
〜array(){/ *销毁初始化元素* /}
// ...
};


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.

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 */ }
    // ...
};