I'm trying to get accumulate2
template working, however it results in compilation errors. I'm not sure why the compiler cannot match the lambda function to this template. Does anyone know whats wrong and how to resolve it? Thanks
#include <iostream>
#include <algorithm>
using namespace std;
template<typename Iter, typename Val>
Val accumulate2(Iter first, Iter last, Val s, Val (*op)(Val&, Val&))
{
while (first!=last) {
s = op(s,*first);
++first;
}
return s;
}
template<typename Iter, typename Val, typename Oper>
Val accumulate(Iter first, Iter last, Val s, Oper op)
{
while (first!=last) {
s = op(s,*first);
++first;
}
return s;
}
int main(int argc, char *argv[])
{
int a[] = {1, 2};
int v0 = accumulate(a, a+2, 0, [](int _v0, int _v1){return _v0 + _v1;});
cout << v0 << endl;
int v1 = accumulate2(a, a+2, 0, [](int _v0, int _v1){return _v0 + _v1;});
cout << v1 << endl;
}
Compilation:
clang++ -std=c++11 -pedantic -Wall test166.cc && ./a.out
test166.cc:30:14: error: no matching function for call to 'accumulate2'
int v1 = accumulate2(a, a+2, 0, [](int _v0, int _v1){return _v0 + _v1;});
^~~~~~~~~~~
test166.cc:6:5: note: candidate template ignored: could not match
'Val (*)(Val &, Val &)' against '(lambda at test166.cc:30:37)'
Val accumulate2(Iter first, Iter last, Val s, Val (*op)(Val&, Val&))
^
1 error generated.
Aucun commentaire:
Enregistrer un commentaire