[英]Lisp like C++ function calling with std::tuple and fold expressions
[英]how to write a fold /sum function for C++ tuple?
我想為std::tuple
編寫一個fold
函數,它可以計算給定元組中所有元素的總和(或乘積)。 例如,給定
std::tuple<int,double> t = std::make_tuple(1,2);
我想算一下
auto s = sumT(t); //giving 3
我試過但是無法在下面編譯我的模板編程(c ++ 11 / 1z)代碼。 我也嘗試將接受的答案改編為我的另一個問題( 如何在C ++中執行元組算術(c ++ 11 / c ++ 17)? ),但是在這種情況下無法弄清楚如何使用std::index_sequence
。
我遇到的問題是:
1)我無法弄清楚類型,例如如何使用第一個元素的類型作為返回類型。 目前,我在模板中使用_res
類型,但我不知道是否會阻止c ++的自動類型推理。
2)我想在不使用顯式初始元素0
情況下對其進行編程,以便可以將其用於其他類型的fold
操作。
目前,遞歸在最后一個元素處結束。 我想在_size - 1
結束遞歸,這樣我就可以直接對最后一個元素執行操作而不需要求助於0
。
我下面的代碼試圖通過遞歸來做到這一點。 但我不熟悉模板編程,以及循環如何為元組工作。
有人可以幫助修復代碼或提出更好的解決方案嗎?
到目前為止我的代碼是:
#include <tuple>
#include <iostream>
#include <functional>
// helper class for fold operations
template<typename Op,typename _res, typename _Tp, size_t _i, size_t _size>
struct _tuple_fold {
static constexpr _res _op(Op const & op, const _Tp& _t) {
return _res(op(std::get<_i>(_t),
_tuple_fold<Op, _res, _Tp, _i + 1, _size>::_op(op,_t) ));
}
};
template<typename Op,typename _res,typename _Tp, size_t _size>
struct _tuple_fold<Op, _res,_Tp, _size, _size> {
static constexpr _res _op(Op const &, const _Tp&) { return 0; }
};
template <typename ... Ts>
auto sumT (std::tuple<Ts...> const & t1) {
return _tuple_fold::_op(std::plus<>{}, t1);
}
int main () {
std::tuple<int,double> t = std::make_tuple(1,2);
auto s = sumT(t);
std::cout << s << std::endl;
}
使用g++ -std=c++17 tuple_sum.cpp
編譯的錯誤消息g++ -std=c++17 tuple_sum.cpp
:
tuple_sum.cpp: In function ‘auto sumT(const std::tuple<_Elements ...>&)’:
tuple_sum.cpp:21:10: error: ‘template<class Op, class _res, class _Tp, long unsigned int _i, long unsigned int _size> struct _tuple_fold’ used without template parameters
return _tuple_fold::_op(std::plus<>{}, t1);
^
tuple_sum.cpp: In function ‘int main()’:
tuple_sum.cpp:27:19: error: ‘void s’ has incomplete type
auto s = sumT(t);
^
我不確定如何在調用站點上為_tuple_fold
提供類型參數,尤其是std::plus
的類型。
請注意,在c ++ 17中我們可以應用()和折疊 :
auto t = std::make_tuple( 1, 2. );
auto sum = std::apply([]( auto... v ){ return ( v + ... ); }, t );
這適用於任何類似元組的類型,並遵循開箱即用的“+”常用促銷/轉換規則(這可能是也可能不是可取的)。 在上面我通過值傳遞,因為我們正在處理算術類型,但你可以應用你喜歡的轉發策略...
值得慶幸的是, if constexpr
c ++ 17中的if constexpr
允許我們通過引入部分專用的輔助結構來避免使事情變得復雜,並且可以在任何我們想要的條件下輕松終止遞歸:
#include <functional>
#include <iostream>
#include <tuple>
#include <type_traits>
template <size_t index, class Op, class... Ts>
constexpr auto tuple_fold(Op op, const std::tuple<Ts...>& t) {
if constexpr(index == sizeof...(Ts) - 1) {
return std::get<index>(t);
} else {
return op(std::get<index>(t), tuple_fold<1 + index>(op, t));
}
}
template <typename ... Ts>
constexpr auto sumT (std::tuple<Ts...> const & t1) {
return tuple_fold<0>(std::plus<>{}, t1);
}
int main () {
std::tuple<int,double> t = {1, 2.0};
auto s = sumT(t);
static_assert(std::is_same_v<decltype(s), double>);
std::cout << s << std::endl;
}
Coliru鏈接: http ://coliru.stacked-crooked.com/a/1e7051b8652fb942
這將執行右側折疊, a + (b + (c + ...))
但如果您願意,可以輕松地重寫它以執行左側折疊。
我們可以利用c ++ 17的左右折疊內置函數來折疊任何二進制操作。
template<class F, class Lhs=void>
struct invoke_by_times_t {
F& f;
Lhs lhs;
template<class Rhs>
auto operator*( Rhs&& rhs )&&
->invoke_by_times_t<F, std::invoke_result_t< F&, Lhs, Rhs >>
{
return {
f,
f(std::forward<Lhs>(lhs), std::forward<Rhs>(rhs))
};
}
};
template<class F>
struct invoke_by_times_t<F, void> {
F& f;
template<class Rhs>
invoke_by_times_t<F, Rhs> operator*( Rhs&& rhs )&&{
return {f, std::forward<Rhs>(rhs)};
}
};
template<class F>
auto fold_over( F&& f ) {
return [f=std::forward<F>(f)](auto&&...args)mutable{
return ( invoke_by_times_t<F>{f}*...*decltype(args)(args) ).lhs;
};
}
現在給定任何二元函數,我們可以創建一個折疊它的函數對象,而不進行任何遞歸。
與std::apply
一起完成。
template <typename ... Ts>
auto sumT (std::tuple<Ts...> const & t1) {
return std::apply( fold_over(std::plus<>{}), t1);
}
這是一個左側折疊。 右側折疊只需更改fold_over
功能。 如果您嘗試將空包傳遞給它,則無法編譯。 如果你傳遞一個元素,它將返回該元素。
#include <tuple>
#include <utility>
namespace detail {
template<class F, class T>
struct foldable : std::pair<const F&, T> {
using std::pair<const F&, T>::pair;
template<class V>
constexpr decltype(auto) operator&&(foldable<F, V>&& x) {
return detail::foldable {
this->first,
this->first(this->second, x.second),
};
}
};
template<class F, class T> foldable(const F&, T&&) -> foldable<F, T>;
}
// Folds left a parameter pack
template<class F, class... Args>
constexpr decltype(auto) fold_left_pack(const F& f, Args&&... args) {
static_assert(sizeof...(Args) > 0, "Cannot fold an empty pack.");
return (... && detail::foldable { f, std::forward<Args>(args) }).second;
}
// Folds right a parameter pack
template<class F, class... Args>
constexpr decltype(auto) fold_right_pack(const F& f, Args&&... args) {
static_assert(sizeof...(Args) > 0, "Cannot fold an empty pack.");
return (detail::foldable { f, std::forward<Args>(args) } && ...).second;
}
// Folds left a tuple
template<class F, class Tuple>
constexpr decltype(auto) fold_left(const F& f, Tuple&& tuple) {
return std::apply(
[&](auto&&... args) -> decltype(auto) {
return fold_left_pack(f, std::forward<decltype(args)>(args)...);
},
std::forward<Tuple>(tuple));
}
// Folds right a tuple
template<class F, class Tuple>
constexpr decltype(auto) fold_right(const F& f, Tuple&& tuple) {
return std::apply(
[&](auto&&... args) -> decltype(auto) {
return fold_right_pack(f, std::forward<decltype(args)>(args)...);
},
std::forward<Tuple>(tuple));
}
一個測試:
constexpr auto divide = [](auto x, auto y) { return x / y; };
constexpr auto tuple = std::make_tuple(8, 4, 2);
static_assert(1 == fold_left(divide, tuple));
static_assert(4 == fold_right(divide, tuple));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.