Re: template + lambda function matching - howto
On 30 Jan., 13:57, Helmut Jarausch wrote:
template <typename Element>
void QuickSort( vector<Element>& V, int lo, int hi,
bool less(const Element& A, const Element& B) ) { ... }
and lateron
vector<int> V;
QuickSort(V,0,49, [](const int& A, const int& B)->bool {return A<B;} );
gcc complains:
template argument deduction/substitution failed:
mismatched types 'bool (*)(const Element&, const Element&)' and
'main()::<lambda(const int&, const int&)>'
Is this a bug in gcc or am I missing something.
You are missing something. The declaration for the last parameter is
a deducible context but the lambda's closure type is only convertible
to a function pointer.
What can I do to make it conform to the standard?
Disable template parameter deduction for the last parameter. You can
do this with an "indirection":
template<class T> struct id{typedef T type;};
template <typename Element>
void QuickSort( vector<Element>& V, int lo, int hi,
typename id<bool(*)(const Element&,const Element&)>::type less);
(untested)
But the more idiomatic solution would be to use an additional template
parameter for an arbitrary functor:
template <class T, class Cmp>
void QuickSort(vector<T>& vec, int lo, int hi, Cmp && less);
(To prevent unnecessary copying I used &&. I guess you want to
implement this recursivly.)
This way, you're also making it very easy for the compiler to inline
the comparator's code directly into the sort function.
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]