如何使用非类型模板参数传入指向数组的指针

How to use nontype template parameters to pass in a pointer to an array?

本文关键字:数组 指针 参数 何使用 类型      更新时间:2023-10-16

这段代码是我在动态编程中实现独木舟租赁问题的一部分。

我在堆上动态分配一个2-D数组,并将返回的地址保存到指向数组的指针类型的变量中。2-D矩阵本身是一个完美的N*N平方。我使用这种非正统的方法,因为数组是按行主顺序存储的,以便将其存储到缓存中。

然后,我想将指向数组的指针传递到一个函数中,以便填充该表。我使用了一个非类型模板参数,因为我可能正在传递一个指向不同大小数组的指针。我事先不知道矩阵的大小,这是由用户的输入决定的。

这是我的密码。我使用CCD_ 1是因为我知道矩阵中的每个值将是数字<256.

#include <cstdint>   // for uint8_t
#include <cstdlib>   // for size_t, EXIT_SUCCESS
#include <iostream>
#include <vector>
using std::cin;
using std::vector;

template <size_t num_of_stations>
void fillPrices(uint8_t (*&prices)[num_of_stations])
{
}
int main()
{
size_t num_of_stations = 0;
cin >> num_of_stations;
uint8_t (*prices)[num_of_stations] = static_cast<uint8_t(*)[num_of_stations]>( malloc(sizeof(uint8_t[num_of_stations][num_of_stations])) );
fillPrices(prices);
delete[] prices;
prices = nullptr;
return EXIT_SUCCESS;
}

我得到一个编译错误。应该对代码中的哪些内容进行更改以使其可编译?

canoe_rental.cpp: In function ‘int main()’:
canoe_rental.cpp:32:22: error: no matching function for call to ‘fillPrices(uint8_t (*&)[num_of_stations])’
fillPrices(prices);
^
canoe_rental.cpp:11:6: note: candidate: template<long unsigned int num_of_stations> void fillPrices(uint8_t (*&)[num_of_stations])
void fillPrices(uint8_t (*&prices)[num_of_stations])
^
canoe_rental.cpp:11:6: note:   template argument deduction/substitution failed:
canoe_rental.cpp:32:22: note:   variable-sized array type ‘long int’ is not a valid template argument
fillPrices(prices);
^

我认为非类型模板参数比它们的价值更麻烦。因此,我通过将指向数组的指针作为void*传递,并传入指向数组中的元素数量,然后只使用类型转换来解决这个问题。现在,在身体内部,我可以按预期使用数组。它有点不优雅,但它很管用!

void fillPrices(void* ptr, size_t num_of_stations)
{
uint8_t (*prices)[num_of_stations] = static_cast<uint8_t(*)[num_of_stations]>(ptr);
}
// To call the function:
int main() {
// more code here
fillPrices(prices, num_of_stations);
}