【发布时间】:2021-04-19 23:44:47
【问题描述】:
我创建了一个foreach() 函数,它应该打印数组的值,但它告诉我:
没有匹配函数调用'foreach(std::array
&, void(&)(int))'
还有:
不匹配的类型'unsigned int'和'long unsigned int'
但是当我尝试使用vectors 代替数组,或者在第11 行使用template<unsigned int N> 代替unsigned int 时,如果我使用long unsigned int,它工作正常。
那么,为什么我需要使用long unsigned int?
数组的“无匹配函数”错误是什么意思?
#include<iostream>
#include<string>
#include<array>
typedef void(*func)(int);
void print(int value) {
std::cout << "value is : " << value << std::endl;
}
template<unsigned int N>
void foreach(std::array<int, N>& values, func print) {
int value;
for(int i = 0; i < values.size(); i++) {
value = values[i];
print(value);
}
}
int main() {
std::array<int, 4> arr = { 0, 1, 2, 3 };
foreach(arr, print);
return 0;
}
使用向量:
#include<iostream>
#include<string>
#include<vector>
typedef void(*func)(int);
void print(int value) {
std::cout << "value is : " << value << std::endl;
}
void foreach(std::vector<int>& values, func print) {
int value;
for(int i = 0; i < values.size(); i++) {
value = values[i];
print(value);
}
}
int main() {
std::vector<int> v = { 0, 1, 2, 3 };
foreach(v, print);
return 0;
}
【问题讨论】:
-
std::for_each()有什么问题?如果是一对迭代器,为什么不直接包装呢? -
template<size_t N>似乎更适合void foreach