[英]Lisp like C++ function calling with std::tuple and fold expressions
關於 Lisp,我能想到的最基本的事情就是如何調用函數。 對於那些不知道如何在 Lisp 中做到這一點的人來說,是這樣的:
(fun1 a b (fun2 c d))
; c and d are parameters to the function fun2,
; and a, b and the result of fun2 are parameters
; to the function fun 1
好吧,我想在 C++ 中使用 std::tuple 和折疊表達式做類似的事情。 基本上,我有一個包含 2 個元素的元組,第一個是我想調用的 function,第二個是另一個帶有 arguments 的元組。 我能夠使這個概念與 1 function 一起使用,並使用以下代碼將“Lisp 元組”放入另一個元組中:
auto add = [](auto ... args){ return (args + ...); };
auto t1_args = std::make_tuple(10, 5);
auto t1 = std::tie(add, t1_args);
auto t_m = std::tie(t1);
auto result = std::apply([](auto ... args){
return (std::apply(std::get<0>(args), std::get<1>(args...)), ...);
}, t_m);
std::cout << result << std::endl; // prints 15
但是我不能用多個函數,多個“Lisp 元組”,一個在另一個里面。 這里有人可以幫我嗎? 也許用另一種方法來制作“Lisp 元組”,但我真的不知道如何讓它工作。
您必須遞歸地評估每個參數,例如:
template <typename T>
auto eval(T t)
{
return t;
}
template <typename ...Ts>
auto eval(std::tuple<Ts...> tuple)
{
return std::apply([](auto... args){ return std::invoke(eval(args)...); }, tuple);
}
演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.