C++:在原型(prototype)中声明 `auto` 函数返回类型仍然导致在推导错误之前使用 `auto`

标签 c++ prototype auto

我在以下代码片段中编写了一个名为 generate_random_matrix 的函数,其返回类型为 auto。当我将函数放在 main 函数之前时,代码工作正常。但是当我将函数放在 main 函数下面,并在顶部包含一个原型(prototype)时,代码会出现常见的错误

 error: use of ‘auto generate_random_matrix(double, double) [with int rows = 10; int cols = 10]’ before deduction of ‘auto’
     auto test_matrix = generate_random_matrix<10,10>(0, 2);

这是不起作用的实际代码片段。关于为什么这不起作用的任何建议?

#include <vector>
#include <array>
#include <random>
#include <iostream>

std::random_device rd;
std::mt19937 gen(rd());

template <int rows, int cols>
auto generate_random_matrix(double lower_, double upper_);

int main()
{
    auto test_matrix = generate_random_matrix<10,10>(0, 2);
    for (int i = 0; i < 5; ++i)
    {
        for (int j = 0; j < 10; ++j)
        {
            std::cout << test_matrix[i][j] << " ";
        }
        std::cout << "\n";
    }
}


template <int rows, int cols>
auto generate_random_matrix(double lower_, double upper_)
{

    std::vector<std::vector<double>> result;
    std::vector<double> inner_result;
    for (int i = 0; i < rows; i++) {
        inner_result.erase(inner_result.begin(), inner_result.end());
        for (int j = 0; j < cols; j++) {
            inner_result.push_back(std::uniform_real_distribution<double>(lower_, upper_)(gen));
        }
        result.push_back(inner_result);
    }

    return result;
}

最佳答案

正如其他人已经提到的,auto 不能在 main() 中推导出来,因为编译没有从模板函数的前向声明中看到返回类型。

只需将整个定义移到 main() 之前即可使其正常工作:

#include <vector>
#include <array>
#include <random>
#include <iostream>

std::random_device rd;
std::mt19937 gen(rd());

template <int rows, int cols>
auto generate_random_matrix(double lower_, double upper_)
{

    std::vector<std::vector<double>> result;
    std::vector<double> inner_result;
    for (int i = 0; i < rows; i++) {
        inner_result.erase(inner_result.begin(), inner_result.end());
        for (int j = 0; j < cols; j++) {
            inner_result.push_back(std::uniform_real_distribution<double>(lower_, upper_)(gen));
        }
        result.push_back(inner_result);
    }

    return result;
}

int main()
{
    auto test_matrix = generate_random_matrix<10,10>(0, 2);
    for (int i = 0; i < 5; ++i)
    {
        for (int j = 0; j < 10; ++j)
        {
            std::cout << test_matrix[i][j] << " ";
        }
        std::cout << "\n";
    }
}

参见 Live Demo

关于C++:在原型(prototype)中声明 `auto` 函数返回类型仍然导致在推导错误之前使用 `auto`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42733926/

相关文章:

javascript - 将 Javascript "Class"原型(prototype)复制到对象

javascript - JS - 将基类型转变为子类型

javascript - `constructor` 属性的真正用途是什么?

c++ - 用于查找字符串 vector 中元素位置的函数出错 (c++)

c++ - 再次获取 std::map 会更改前一个迭代器

c++ - 来自 const std::vector<>& 的自动;对象还是引用?

c++ - 使用opengl创建交互式对话框

android - Cocos2d-x 3.13.1 : error with cocos run (Android)

c++ - 使用迭代器按索引删除 vector ?

c++ - 避免临时 std::string 调用 boost::unordered_map::find