【问题标题】:How can I replace the auto reference keyword in this code?如何替换此代码中的自动引用关键字?
【发布时间】:2023-01-12 21:00:15
【问题描述】:

您好,我想找到一种方法来替换以下代码中的 auto 关键字。

#include <iostream>

using namespace std;

void printMatrix(const auto & matrix) {
    /* print matrix using range-based for */
}

int main() {
    int matrix[][3] = {{}, {}, {}};
    int matrix2[][6] = {{}, {}, {}};
    printMatrix(matrix);
    printMatrix(matrix2);
    return 0;
}

我应该用什么来替换 const auto & matrix 中的 auto。 我可以使用指针,但问题是我必须传递行和列的大小。 上面的代码有效,但我想知道 auto 关键字如何处理这个问题。

【问题讨论】:

标签: c++


【解决方案1】:

这个函数声明

void printMatrix(const auto & matrix) {
    /* print matrix using range-based for */
}

声明一个模板函数。

相反,你可以写例如

template <typename T, size_t M, size_t N>
void printMatrix(const T ( & matrix)[M][N]) {
    /* print matrix using range-based for */
}

并且该函数被称为前一个函数

printMatrix(matrix);
printMatrix(matrix2);

由于数组的元素类型是已知的,因此您也可以编写

template <size_t M, size_t N>
void printMatrix(const int ( & matrix)[M][N]) {
    /* print matrix using range-based for */
}

//...

printMatrix(matrix);
printMatrix(matrix2);

在函数中,您可以在嵌套的 for 循环中使用值 MN 来输出数组,例如

for ( size_t i = 0; i < M; i++ )
{
    for ( size_t j = 0; j < N; j++ )
    {
        //...
    }
}

或者您可以使用基于范围的 for 循环

for ( const auto &row : matrix )
{
    for ( const auto &item : row )
    {
        //...
    }
}

【讨论】:

    【解决方案2】:

    对于参数化元素类型,重新声明打印函数以仅允许通过引用作为二维数组的函数参数:

    #include <cstddef>  // std::size_t
    
    template<typename T, std::size_t num_rows, std::size_t num_cols>
    void printMatrix(T const (&mat)[num_rows][num_cols]) {
        /* print matrix using range-based for */
    }
    
    
    // ....
    printMatrix(matrix);  // template arguments inferred as <int, 3, 3>
    printMatrix(matrix2); // template arguments inferred as <int, 3, 6>
    

    这本质上是一个更专业的版本,它使用单个类型模板参数(如在 OP 的示例中,通过 auto/abbreviated function template 和一个发明的类型模板参数)。

    【讨论】:

    • @463035818_is_not_a_number 啊是的,缩写函数模板,谢谢。更正。
    【解决方案3】:

    您可以将 auto 替换为模板参数。 这就是 C++ 14 之前的做法。

    #include <iostream>
    
    using namespace std;
    
    template <typename Matrix>
    void printMatrix(const Matrix & matrix) {
        /* print matrix using range-based for */
    }
    
    int main() {
        int matrix[][3] = {{}, {}, {}};
        int matrix2[][6] = {{}, {}, {}};
        printMatrix(matrix);
        printMatrix(matrix2);
        return 0;
    }
    

    【讨论】:

    • “我可以使用指针,但问题是我必须传递行和列的大小。”使用您的方法,尺寸不容易获得。它并不比传递指针+大小更好
    猜你喜欢
    • 2019-08-31
    • 1970-01-01
    • 2017-12-05
    • 2011-12-22
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多