为什么 <iterator> 的 std::size 不能使用原始数组参数
Why is <iterator>'s std::size not working with raw array parameters
我通常在现代 C++ 的最高支持版本是 C++14 的环境中工作。我在 c++17 中试验 <iterator>
中的 std::size
并遇到了以下问题/问题/我缺乏理解。
在下面的代码片段中,size(a)
在 main
中的使用可以正常工作,但 print
中的使用拒绝编译并指出 no matching function for call to 'size(int*&)'
存在。
我知道还有其他更好的方法可以做到这一点,但我想知道为什么它在一种情况下有效,而在另一种情况下无效。
为了它的价值,我使用了以下 online compiler 并简单地打开了 -std=c++17
标志。
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
void print(int a[])
{
for(int i = 0; i < size(a); i++)
cout << a[i] << endl;
}
int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << "Directly" << endl;
for(int i = 0; i < size(a); i++)
cout << a[i] << endl;
cout << "Via function" << endl;
print(a);
return 0;
}
std::size
的第一次调用使用此函数模板签名(重载集中的#3 here):
template <class T, std::size_t N>
constexpr std::size_t size(const T (&array)[N]) noexcept;
其中参数 array
没有衰减为指针。它是一个原始数组,其大小以其类型编码。当您将这样的数组传递给接受 int[]
(或 int*
无关紧要)的函数时,数组会衰减为指针,并且大小不再是类型的一部分。这就是 std::size(a)
无法编译的原因。简明扼要:
Why is <iterator>
's std::size
not working with raw array parameters?
是的,但您试图将它与指针一起使用,而不是数组参数。
我通常在现代 C++ 的最高支持版本是 C++14 的环境中工作。我在 c++17 中试验 <iterator>
中的 std::size
并遇到了以下问题/问题/我缺乏理解。
在下面的代码片段中,size(a)
在 main
中的使用可以正常工作,但 print
中的使用拒绝编译并指出 no matching function for call to 'size(int*&)'
存在。
我知道还有其他更好的方法可以做到这一点,但我想知道为什么它在一种情况下有效,而在另一种情况下无效。
为了它的价值,我使用了以下 online compiler 并简单地打开了 -std=c++17
标志。
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
void print(int a[])
{
for(int i = 0; i < size(a); i++)
cout << a[i] << endl;
}
int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << "Directly" << endl;
for(int i = 0; i < size(a); i++)
cout << a[i] << endl;
cout << "Via function" << endl;
print(a);
return 0;
}
std::size
的第一次调用使用此函数模板签名(重载集中的#3 here):
template <class T, std::size_t N>
constexpr std::size_t size(const T (&array)[N]) noexcept;
其中参数 array
没有衰减为指针。它是一个原始数组,其大小以其类型编码。当您将这样的数组传递给接受 int[]
(或 int*
无关紧要)的函数时,数组会衰减为指针,并且大小不再是类型的一部分。这就是 std::size(a)
无法编译的原因。简明扼要:
Why is
<iterator>
'sstd::size
not working with raw array parameters?
是的,但您试图将它与指针一起使用,而不是数组参数。