(這裏是C++ 11的新手) 與C++ 11個lambda表達式嘗試一些想法組成:C++ 11組成具有的std ::功能失效
#include <iostream>
#include <functional>
struct A { };
struct B { };
struct C { };
B b4a (A a) { B b; return b; }
C c4b (B b) { C c; return c; }
我現在打印出來的類型如下(的type_name
定義是有點偏離主題,但是我有source of everything in this question building and working online here):
cout << "b4a : " << type_name<decltype(b4a)>() << endl;
cout << "c4b : " << type_name<decltype(c4b)>() << endl;
auto c4a = [=] (A a) { return c4b (b4a (a)); };
cout << "c4a : " << type_name<decltype(c4a)>() << endl;
產生以下合理外觀輸出:
b4a : B (A)
c4b : C (B)
c4a : main::{lambda(A)#1}
我現在嘗試抽象成分本身如下:
template <typename R, typename S, typename T>
std::function<R (T)> compose
( std::function <R (S)> r4s
, std::function <S (T)> s4t )
{ return [=] (T t) { r4s (s4t (t)); }; }
,我得到了以下錯誤
main.cpp: In function 'int main()':
main.cpp:44:33: error: no matching function for call to 'compose(C (&)(B), B (&)(A))'
auto c4a = compose (c4b, b4a);
^
main.cpp:44:33: note: candidate is:
main.cpp:34:17: note: template<class R, class S, class T> std::function<R(T)> compose(std::function<R(S)>, std::function<S(T)>)
function<R (T)> compose
^
main.cpp:34:17: note: template argument deduction/substitution failed:
main.cpp:44:33: note: mismatched types 'std::function<R(S)>' and 'C (*)(B)'
auto c4a = compose (c4b, b4a);
這暗示有一個「指針到功能型」的問題;但我認爲std::function<...>
應該抽象出來呢?
在顯式類型參數
auto c4a = compose<C, B, A> (c4b, b4a);
改變了錯誤,但不利於把:
main.cpp: In instantiation of 'std::function<R(T)> compose(std::function<R(S)>, std::function<S(T)>) [with R = C; S = B; T = A]':
main.cpp:44:42: required from here
main.cpp:37:42: error: could not convert '<lambda closure object>compose(std::function<R(S)>, std::function<S(T)>) [with R = C; S = B; T = A]::<lambda(A)>{std::function<C(B)>((*(const std::function<C(B)>*)(& r4s))), std::function<B(A)>((*(const std::function<B(A)>*)(& s4t)))}' from 'compose(std::function<R(S)>, std::function<S(T)>) [with R = C; S = B; T = A]::<lambda(A)>' to 'std::function<C(A)>'
{ return [=] (T t) { r4s (s4t (t)); }; }
在顯式轉換
auto c4a = compose (std::function<C(B)>(c4b), std::function<B(A)>(b4a));
或
auto c4a = compose<C, B, A> (std::function<C(B)>(c4b), std::function<B(A)>(b4a));
把
產生與上述相同的錯誤。線索?
我忘了在上面了'return'。請參閱http://coliru.stacked-crooked.com/a/8cb674b2bddeb2c0 –