I try to write a forEach method (I know that already exists but I will try it on my own)
This is my code:
#include <iostream>
#include <array>
#include <functional>
using namespace std;
template<typename T, std::size_t SIZE>
void forEach(std::array<T, SIZE> array, function<void(int)> fun){
for(auto const & object: array)
fun(object);
}
int main()
{
std::array<int, 4> num{1,2,3,4};
forEach(num, [](int n) -> void { cout << n * n << endl;});
return 0;
}
This works fine.
Now when I change the second parameter of forEach function<void(int)> fun
to function<void(T)> fun
it does not compile and I get the error:
no matching function for call to 'forEach(std::array<int, 4u>&, main()::<lambda(int)>)'
But when I understand it correctly T
should be int
in this example.
Do I make a thinking mistake?
Why it doesn't work?
It works when I do it on this way:
template<typename T, std::size_t SIZE>
void forEach(std::array<T, SIZE> array, function<void(T)> fun){
for(auto const & object: array)
fun(object);
}
int main()
{
std::array<int, 4> num{1,2,3,4};
function<void(int)> func = [](int n) -> void { cout << n * n << endl;};
forEach(num, func);
return 0;
}
But can I do it directly in the function call like the first code snippet?
Thanks in advance