Sto cercando di scrivere una funzione generica piega utilizzando le nuove funzioni anonime disponibili in C++ 11, qui è quello che ho:Funzioni di ordine superiore in C++ 11
template<typename T>
T foldl(std::function<T(T,T)> f, T initial, std::vector<T> items) {
T accum = initial;
for(typename std::vector<T>::iterator it = items.begin(); it != items.end(); ++it) {
accum = f(accum, (*it));
}
return accum;
}
Il seguente tentativo per usarlo:
std::vector<int> arr;
arr.assign(8, 2);
foldl([] (int x, int y) -> int { return x * y; }, 1, arr);
causa un errore:
main.cpp:44:61: error: no matching function for call to 'foldl(main(int, char**)::<lambda(int, int)>, int, std::vector<int>&)'
main.cpp:44:61: note: candidate is:
main.cpp:20:3: note: template<class T> T foldl(std::function<T(T, T)>, T, std::vector<T>)
main.cpp:20:3: note: template argument deduction/substitution failed:
main.cpp:44:61: note: 'main(int, char**)::<lambda(int, int)>' is not derived from 'std::function<T(T, T)>'
mi sembra che l'uso di std::function
non è il giusto wa y per definire il tipo di f
. Come posso correggere questo?
C'è qualcosa di sbagliato [con 'std :: accumulate'] (http://en.cppreference.com/w/cpp/algorithm/accumulate)? –
Sto solo giocando in C++ e volevo scrivere il mio. – defectivehalt