Reputation: 13
I am working with lambdas for the first time. I am supposed to write a function walk() which takes a lambda function as a parameter.
In the header I declared said function as:
template<class T>
void walk(T operation) const;
We are supposed to define the function in an .inl, which I have done like this:
template<class T>
void Sea::Grid2D<T>::walk(T operation) const{
for(auto a : Sea::Grid2D<T>::grid){
operation(a);
}
}
My question comes in at this point, since we are given a test class, which calls our walk() function like this.
grid.walk([&](int const &cell) { sum += cell; });
This call of the walk function results in the following error:
error: cannot convert 'testWalkAndFilter()::<lambda(const int&)>' to 'int'
43 | grid.walk([&](int const &cell) { sum += cell; });
How would I go about converting my lambda function into the int or needed parameter?
While trying to solve this problem. I've also tried to give the walk function a reference, or a const reference parameter, but nothing has worked so far.
Upvotes: 1
Views: 157
Reputation: 66459
You have instantiated Sea::Grid2D<int>
- that is, T
is int
- which gives you:
void Sea::Grid2D<int>::walk(int operation) const {
for(auto a : Sea::Grid2D<int>::grid) {
operation(a);
}
}
which fairly obviously has a typing problem - the type of the operation should not be the same as the type of your grid elements.
Since you have a function template inside of a class template, you need two "levels" of templating, e.g.:
template<class T>
class Grid2D {
...
template <class Fn>
void walk(Fn operation) const;
...
};
...
template<class T>
template <class Fn>
void Sea::Grid2D<T>::walk(Fn operation) const {
for(auto a : grid) {
operation(a);
}
}
Upvotes: 5
Reputation: 13552
You are probably using the name T
for 2 different arguments (I guess one at the Grid2D class level and one on this function).
template<class T>
void Sea::Grid2D<T>::walk(T operation) const{
for(auto a : Sea::Grid2D<T>::grid){
Rename this one to something else. Like, U
.
But it's better to give them name that reflect the intent, if possible. Like, Callable
or Operation
.
Upvotes: 1