gpt4 book ai didi

带有 std::function 的 C++11 组合失败

转载 作者:太空宇宙 更新时间:2023-11-04 11:32:16 25 4
gpt4 key购买 nike

<分区>

(这里是 C++11 新手)使用 C++11 lambda 尝试一些组合想法:

#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));

产生与上述相同的错误。线索?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com