为什么std::size()
不适用于按值传递的静态分配数组?
void print_elemTab(int tab[])
{
// ...
int size = std::size(tab); //error
// ...
}
void test_tab()
{
const int TAB_SIZE = 5;
int tab[TAB_SIZE] = {};
// ...
cout << std::size(tab) << std::endl; //print 5
print_elemTab(tab);
// ...
}
我正在打印尺寸,然后通过 tab
在子功能print_elemTab()
我在哪里使用 std::size()
再次。我没有得到匹配函数错误,所以我想知道为什么
std::size()
第一次工作在test_tab()
而不是在 print_elemTab()
我必须通过引用传递它吗?那么我如何制作它,但对于任意长度的数组呢?还是因为我不知道的事情我必须以另一种方式制作它?
最佳答案
Do I have to pass it by reference? And so how do I make it but for any array of any length?
是 ,通过引用传递它是一种选择。
template<std::size_t n>
void print_elemTab(int (&tab)[N]) // const int (&tab)[N], if the elements won't be modified
{
std::cout << N << "\n"; // where you can directly get the size `N`
}
或者像简单的模板化函数如下
template<typename T>
void print_elemTab(T& tab)// const T& tab, if the elements won't be modified
{
const auto size = std::size(tab);
std::cout << size << "\n";
}
另一种选择是将数组推导出其实际类型。在您的情况下,
tab
有类型 int[5]
.如果您 perfectly forward,编译器可以推断出它的实际类型(而不是衰减到指针)通过模板函数。#include <iostream>
#include <array>
template<typename T>
void print_elemTab(T&& tab)
{
const auto size = std::size(tab); // now you can do std::size() on the int[size]
std::cout << size << "\n";
}
关于c++ - 为什么按值传递的数组上的 std::size 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62486307/