c++ - 为什么按值传递的数组上的 std::size 不起作用?
问题描述
为什么对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()
我必须通过引用传递它吗?那么,除了任意长度的数组,我该怎么做呢?
还是因为我不知道的事情,我必须以另一种方式做到这一点?
解决方案
我必须通过引用传递它吗?那么,除了任何长度的数组之外,我该怎么做呢?
是的,通过引用传递它是一种选择。
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
具有 type int[5]
。如果您通过模板函数完美转发,编译器可以推断出它的实际类型(而不是衰减为指针)。
#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";
}
推荐阅读
- firebase - 将数据上传到 Firestore 中的多个文档的最佳方法
- javascript - 模态未关闭
- next.js - Travis Build 卡在构建新包步骤上
- php - 在 for 循环中过滤 PHP 帖子
- c# - 如何准备与 dapper 的一对多关系
- node.js - 如何使用 sequelize 查询另一个数据库?
- java - Android Studio 凌空字符串请求返回空公共数组
- r - 当我将带有乳胶表的 Rmarkdown 文档转换为 docx 时缺少表
- flutter - 如果你运行一个用 Flutter 制作的应用程序并进入主屏幕一段时间,会不断出现以下消息
- python - Asyncio 在函数内将标识符附加到协程会引发异常