我正在玩C++ 14 lambdas(一般来说只是lambdas)我有一个函数(管道)我正在尝试编写.前提是它需要一个单位lambda和一组一元lambda然后它将在单元上运行并产生一个新单元发送到管道中的下一个单元,直到你通过最后一个lambda并返回最后一个单元.我目前的代码是:
auto pipeline = [](auto u, auto callbacks[]){
for(int i = 0; i<sizeof(callbacks)/sizeof(callbacks[0]);i++){
u = bind(u,callbacks[i]);
}
return u;
};
Run Code Online (Sandbox Code Playgroud)
目前的问题是,clang正在回击阵列说:
testFuture.cpp:183:111: error: no matching function for call to object of type 'func::<lambda at ./func.hpp:30:19>'
cout<<"pipeline(unit(10),{addf(4),curry(mul,2)}):"<<bind(unit(bind(unit(10))(addf(4))))(curry(mul,2))<<"|"<<pipeline(unit(10),{{addf(4),curry(mul,2)}})()<<endl;
^~~~~~~~
./func.hpp:30:19: note: candidate template ignored: couldn't infer template argument '$auto-0-1'
auto pipeline = [](auto u, auto callbacks[]){
^
1 error generated.
Run Code Online (Sandbox Code Playgroud)
这是不可能与lambdas?我需要甩出来std::function
吗?我只是以错误的方式解决这个问题吗?
退后一步,你试图在一系列值上执行(左)折叠.因为在C++中,每个闭包都有一个唯一的类型,所以你想在元组上进行折叠,而不是数组.作为一个额外的好处,我们将更加通用并接受具有任何返回类型的仿函数,如果我们用来std::function
模拟箭头类型,我们就不能这样做.
#include <utility> // std::forward, std::integer_sequence
#include <type_traits> // std::remove_reference_t
#include <tuple> // tuple protocol, e.g. std::get, std::tuple_size
namespace detail {
template<typename Functor, typename Zero, typename Tuple, typename Int>
Zero foldl(Functor&&, Zero&& zero, Tuple&&, std::integer_sequence<Int>)
{ return std::forward<Zero>(zero); }
template<typename Functor, typename Zero, typename Tuple, typename Int, Int Index, Int... Indices>
decltype(auto) foldl(Functor&& functor, Zero&& zero, Tuple&& tuple, std::integer_sequence<Int, Index, Indices...>)
{ return detail::foldl(
functor
, functor(std::forward<Zero>(zero), std::get<Index>(std::forward<Tuple>(tuple)))
, std::forward<Tuple>(tuple)
, std::integer_sequence<Int, Indices...> {}); }
} // detail
template<typename Functor, typename Zero, typename Tuple>
decltype(auto) foldl(Functor&& functor, Zero&& zero, Tuple&& tuple)
{
return detail::foldl(
std::forward<Functor>(functor)
, std::forward<Zero>(zero)
, std::forward<Tuple>(tuple)
, std::make_index_sequence<std::tuple_size<std::remove_reference_t<Tuple>>::value>()
);
}
Run Code Online (Sandbox Code Playgroud)
你没有告诉我们bind
应该达到的目标,但这里有一个涉及功能逆向组合的例子.(包括有限的实施integer_sequence
和朋友,因为他们似乎没有在Coliru上可用 - 类型特征也缺少别名.)