是否可以在C++20中实现泛型多功能函数组合/流水线?
struct F{//1st multi-functor template<typename T> void operator()(const T& t){/*...*/} }; struct G{//2nd multi-functor template<typename T> void operator()(const T& t){/*...*/} }; F f; G g; auto pipe = f | g;//what magic should happen here to achieve g(f(...)) ? how exactly to overload the operator|()? pipe(123); //=> g(f(123); pipe("text");//=> g(f("text");
编辑: 我尝试了这两个建议(来自@Some_Programmer_DUD和@Jarod42),但我在错误中迷失了方向:
- 重载运算符|()Like@Some_Programmer_DUD建议
template<class Inp,class Out> auto operator|(Inp inp,Out out){ return [inp,out](const Inp& arg){ out(inp(arg)); }; }
生成:
2>main.cpp(71,13): error C3848: expression having type 'const Inp' would lose some const-volatile qualifiers in order to call 'void F::operator ()<F>(const T &)' 2> with 2> [ 2> Inp=F 2> ] 2> and 2> [ 2> T=F 2> ]
- 像@Jarod42建议的那样,直接使用lambda而不是重载运算符|():
auto pipe = [=](const auto& arg){g(f(arg));};
生成:
2>main.cpp(86,52): error C3848: expression having type 'const F' would lose some const-volatile qualifiers in order to call 'void F::operator ()<_T1>(const T &)' 2> with 2> [ 2> _T1=int,2> T=int 2> ]