Why does this code have error C2784 "could not print the template"

From the lambda function passed as parameter I can compile an example:

template <class Range> Range FindFirstIf(Range, bool(*Function)(typename Range::ConstReference value)); struct range { using ConstReference = const float&; }; range rng; rng = FindFirstIf(rng, [](const float& val) { return (val < 0.0f); }); 

Of course, it cannot reference because FindFirstIf not implemented.

However, when I did a similar thing:

 template <class Range, class ValueType> Range MyTest(Range, ValueType, bool(*Function)(ValueType value)); std::vector <int> vi; double d = 0; vi = MyTest(vi, d, [](double val) { return (val < 0.0f); }); 

He has a compilation error:

error C2784: "Range MyTest (range, ValueType, bool (__cdecl *) (ValueType)) ': could not derive the template argument for' bool (__cdecl *) (ValueType) 'from' Home :: '

why is that? I thought skipping d in, ValueType can be inferred as double ?

+5
source share
1 answer

Use this instead (note the + ):

 vi = MyTest(vi, d, +[](double val) { return (val < 0.0f); }); 

Lambda functions may in some cases fade out in function pointers, but they are not function pointers for themselves.
In other words, the deduction fails because it expects to work with a pointer to a function, but lambda is not a pointer to a function, it can, of course, be converted, but deduction must be done first, but it cannot be that the lambda does not was the expected type, it can decay into it ... And so on.
By adding + before the lambda, you force the conversion before it is passed to the function, so MyTest will get the actual function pointer, as expected, and the deduction continues.

The following is a minimal working example based on your code:

 #include<vector> template <class Range, class ValueType> Range MyTest(Range, ValueType, bool(*Function)(ValueType value)) {} int main() { std::vector <int> vi; double d = 0; vi = MyTest(vi, d, +[](double val) { return (val < 0.0f); }); } 
+2
source

Source: https://habr.com/ru/post/1258382/


All Articles