尝试一些构图的想法,我有
#include <iostream>
#include <functional>
using namespace std;
struct A { };
struct B { };
struct C { };
B b4a (A a) { B b; return b; }
C c4b (B b) { C c; return c; }
template <typename R, typename S, typename T>
function<R(T)> composition
( R(r4s)(S)
, S(s4t)(T) )
{ return [=] (T t) { return r4s (s4t (t)); }; }
int main()
{
cout << "b4a : " << type_name<decltype(b4a)>() << endl;
cout << "c4b : " << type_name<decltype(c4b)>() << endl;
auto c4a = composition<C, B, A> (c4b, b4a);
cout << "c4a : " << type_name<decltype(c4a)>() << endl;
auto lb4a = [=] (A a) { B b; return b; };
auto lc4b = [=] (B b) { C c; return c; };
auto lc4a = composition<C, B, A>(lc4b, lb4a);
cout << "lc4a : " << type_name<decltype(lc4a)>() << endl;
}
(的定义type_name
有点题外话,但您可以在此处看到以上内容的完整工作示例)。
您会看到此composition
运算符可用于的函数指针b4a
和的lambda lb4a
。我想摆脱的function<R(T)>
返回类型composition
,而直接声明其类型,但是我不知道如何以其他方式表示其返回类型。尝试中
R(composition)(T)
要么
R(*composition)(T)
要么
R(&composition)(T)
产生'composition' declared as function returning a function
,导致我怀疑这是不可能的。线索?
Lambda具有唯一但未指定的类型。一种可能的解决方法是不使用lambda,而是创建自己的等效类:
template <typename R, typename S, typename T>
struct Composition {
R (*r4s)(S);
S (*s4t)(T);
R operator()(T t) const { return r4s(s4t(t)); }
};
template <typename R, typename S, typename T>
Composition<R,S,T> composition(R (*r4s)(S),S(*s4t)(T))
{
return {r4s,s4t};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句