почему лямбда-функции в с ++ 11 не имеют функций <>?
Я играю с функциональными возможностями C ++ 11. Единственное, что я нахожу странным, это то, что тип лямбда-функции на самом деле НЕ является функцией & lt; & gt; тип. Более того, лямбда, кажется, не очень хорошо работает с механизмом определения типа.
В приложении приведен небольшой пример, в котором я протестировал переключение двух аргументов функции для добавления двух целых чисел. (Компилятор, который я использовал, был gcc 4.6.2 под MinGW.) В примере тип дляaddInt_f
был явно определен с использованием функции & lt; & gt; в то время какaddInt_l
лямбда, тип которого определяется типомauto
.
Когда я скомпилировал код,flip
Функция может принимать явно определенную типовую версию addInt, но не лямбда-версию, выдавая ошибку о том, что
testCppBind.cpp:15:27: error: no matching function for call to 'flip(<lambda(int, int)>&)'
Следующие несколько строк показывают, что лямбда-версия (а также «необработанная» версия) может быть принята, если она явно приведена к соответствующей функции & lt; & gt; тип.
Итак, мои вопросы:
Why is it that a lambda function does not have a function<>
type in the first place? In the small example, why does not addInt_l
have function<int (int,int)>
as the type instead of having a different, lambda
type? From the perspective of functional programming, what's the difference between a function/functional object and a lambda?
If there is a fundamental reason that these two have to be different. I heard that lambda's can be converted to function<>
but they are different. Is this a design issue/defect of C++11, an implementation issue or is there a benefit in distinguishing the two as the way it is? It seems that the type-signature of addInt_l
alone has provided enough information about the parameter and return types of the function.
Is there a way to write the lambda so that the above mentioned explicit type-casting can be avoided?
Заранее спасибо.
//-- testCppBind.cpp --
#include <functional>
using namespace std;
using namespace std::placeholders;
template <typename T1,typename T2, typename T3>
function<T3 (T2, T1)> flip(function<T3 (T1, T2)> f) { return bind(f,_2,_1);}
function<int (int,int)> addInt_f = [](int a,int b) -> int { return a + b;};
auto addInt_l = [](int a,int b) -> int { return a + b;};
int addInt0(int a, int b) { return a+b;}
int main() {
auto ff = flip(addInt_f); //ok
auto ff1 = flip(addInt_l); //not ok
auto ff2 = flip((function<int (int,int)>)addInt_l); //ok
auto ff3 = flip((function<int (int,int)>)addInt0); //ok
return 0;
}