首页 > 解决方案 > 为什么按值传递的数组上的 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()

我必须通过引用传递它吗?那么,除了任意长度的数组,我该怎么做呢?

还是因为我不知道的事情,我必须以另一种方式做到这一点?

标签: c++arraysc++17pass-by-reference

解决方案


我必须通过引用传递它吗?那么,除了任何长度的数组之外,我该怎么做呢?

的,通过引用传递它是一种选择。

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";
}

推荐阅读