遇到一个 c++ 类型推导相关的问题

查看 41|回复 2
作者:Thymolblue   
由于其他模块把一个二维数据存成的一维数组, 给我传参时会给我首地址和数据的长宽. 如test1()所示,我可以建一个二维数组的指针去指向数据的头, 并对数据进行操作. 所以我就在想能否写一个函数去完成test1()的工作. 在test2()函数里是时可以完成test1()的工作, 但是返回值并没有达到工作预期. 使用auto result只能访问到数组第一个元素, 使用auto &result无法通过编译.
环境:
  • MinGW64 7.3.0, Qt 5.12.12
  • MinGW64 11.2.0, Qt 6.5.2
  • C++ 17
  • Windows 10

    在 MSVC 2019 编译器下 test1() 的代码无法通过编译, 会提示数组的边界必须在编译期确定.
    问题:
  • test1()中算是运行期间创建了一个类型吗?
  • 是否可能用函数实现test1()中前两行的代码并将数据传出去?

    #include
    #include
    void test1(float *raw, int sizex, int sizey)
    {
        using DataType = float[sizex][sizey];
        auto &data = *reinterpret_cast(raw); // 编译通过, 并可以使用迭代器
        // auto &data = *reinterpret_cast(raw);
        // 编译无法通过, 错误如下:
        // error: Expected a type
        for (auto &row: data)
        {
            for (auto &item: row)
            {
                std::cout
    auto test2(T *t, int sizex, int sizey)
    {
        using DataType = T[sizex][sizey];
        auto ptr = reinterpret_cast(t);
        return ptr;
    }
    int main()
    {
        int sizex = 3;
        int sizey = 4;
        std::vector vc(sizex * sizey);
        for (int i = 0; i

    sizex, sizey, auto, int

  • inhzus   
    C-style array 的大小就应该是 constant expression... 不要钻这个牛角尖,不要写 mingw 方言... 不如老老实实就用 (T**, size_x, size_y) 来替代你的 T[size_x][size_y] *
    Thymolblue
    OP
      
    @inhzus 其他模块给我的就只有数据块头的地址,不是很好更改。其实去计算访问的每个元素的地址也可以,但是如果能把这个指针转成二维数组的话我就可以对数据封装一下,后面的计算会简化很多。
    您需要登录后才可以回帖 登录 | 立即注册

    返回顶部