Thursday, 15 May 2014

c++ - Couldn't deduce template parameter from function parameter's default argument -



c++ - Couldn't deduce template parameter from function parameter's default argument -

i'm trying create function finds minimum element in range satisfies given condition:

#include <functional> #include <iostream> #include <vector> template <typename it, typename pred, typename comp> minelementwhere( begin, end, pred pred = pred(), // utilize less-than default comparator. comp comp = std::less<decltype(*std::declval<it>())>() ) { minelement = end; (it = begin; != end; ++it) { if (!pred(*it)) { continue; } if (comp(*it, *minelement)) { minelement = it; } } homecoming minelement; } int main() { std::vector<double> foo; foo.push_back(6); foo.push_back(10); foo.push_back(-3); foo.push_back(7); std::cout << *minelementwhere( foo.begin(), foo.end(), [](double val) { homecoming val >= 0; } ) << std::endl; }

but error:

main.cpp: in function 'int main()': main.cpp:40:5: error: no matching function phone call 'minelementwhere(std::vector<double>::iterator, std::vector<double>::iterator, main()::__lambda0)' ) << std::endl; ^ main.cpp:40:5: note: candidate is: main.cpp:6:4: note: template<class it, class pred, class comp> minelementwhere(it, it, pred, comp) minelementwhere( ^ main.cpp:6:4: note: template argument deduction/substitution failed: main.cpp:40:5: note: couldn't deduce template parameter 'comp' ) << std::endl;

comp isn't homecoming type, it's not trying deduce homecoming type, , doesn't seem me there ambiguous overloads of comp (since there can 1 homecoming type of dereferencing it). why getting error, , how can prepare it?

you're expecting template parameter comp deduced default argument provided corresponding function parameter. however, explicitly listed non-deduced context, meaning template argument deduction fail template parameter (unless can deduced elsewhere).

from §14.8.2.5/5 [temp.deduct.type]

the non-deduced contexts are: — ... — template parameter used in parameter type of function parameter has default argument beingness used in phone call argument deduction beingness done.

to have template argument deduction succeed, provide default argument template parameter, instead of function parameter.

template <typename it, typename pred, typename comp = std::less<decltype(*std::declval<it>())>> minelementwhere( begin, end, pred pred = pred(), comp comp = comp() ) { ... }

live demo

c++ templates c++11

No comments:

Post a Comment