I wrote a simple function which gives me an index when using std::for_each
over an iterator. The function is as follows:
template<typename It, typename I = std::size_t>
void for_each_indexed(It begin,
It end,
void l(typename std::iterator_traits<It>::value_type, I),
I counter = 0) {
std::for_each(begin, end,
[&counter, &l](typename std::iterator_traits<It>::value_type value) {
l(value, counter);
counter++;
});
};
My problem is that, when I pass a lambda to this function, I get an error like the following:
test.cpp:40:6: error: no matching function for call to ‘for_each_indexed(std::__cxx11::
basic_string<char>::iterator, std::__cxx11::basic_string<char>::iterator, crossOutChar(
std::__cxx11::string&, char)::<lambda(char, size_t)>)’
});
^
test.cpp:18:6: note: candidate: ‘template<class It, class I> void for_each_indexed(It,
It, void (*)(typename std::iterator_traits<_Iter>::value_type, I), I)’
void for_each_indexed(It begin,
^~~~~~~~~~~~~~~~
test.cpp:18:6: note: template argument deduction/substitution failed:
test.cpp:40:6: note: mismatched types ‘void (*)(typename std::iterator_traits<_Iter>:
:value_type, I)’ and ‘crossOutChar(std::__cxx11::string&, char)::<lambda(char, size_t)’
});
^
The following compiles and runs:
void process(char c, size_t i) {}
void crossOutChar(std::string &s, char c) {
for_each_indexed(s.begin(), s.end(), process);
}
but the following does not:
void
crossOutChar(std::string &s, char c) {
auto process = [c, &s](char c2, size_t i) {
if (c == c2) {
s[i] = '*';
}
};
for_each_indexed(s.begin(), s.end(), process);
}
What could be the error in here? Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire