Fold expressions with arbitrary callable?

我的梦境 提交于 2019-12-03 10:23:21

That's a great paper and a glorious language feature. If we bypass the standardese talk, which I'm not particularly fond of, I'd like to propose a workaround. Since I don't have a c++17 compiler (or a time machine) my answer will only be outlining, what I believe could be, a solution to providing fold expressions with arbitrary functions with the language status as is.

1. Define a type wrapper (a lightweight one)

template<typename T>
struct wp {
    T const& val; 
    // yes there should be constructors
};

2. Machinery to transform packs to wrapped packs

template<typename Op, typename Ts...>
using wrapped_pack = make_wrapped<Op, Ts..>

3. Overload a built in operator for wp<T>

template<typename T, typename U>
ret_val operator+(wp<T> const& lhs, wp<U> const& rhs) {...}

4. Use the wrapped pack in the fold expression

This would require an extra layer where the args of the fold are transformed to wrapped arguments


An obvious shortcoming of the above is that it doesn't guarantee uniqueness (or scalability) : every fold with a custom functor would consume a built in operator overloading.

There should be hacks to vary the types based on the expression they're encountered in but I don't want to dive that deep into a thought experiment (eg using the type of Op in the type of the wrapper already gives much more space to scale into).

Lorah Attkins

First of all I'm happy that what I wrote works in clang (I see your update implements 3 out of the 4 steps I mention). I have to give credit to Nick Athanasiou for this technique that discussed this with me way before writing this.

The reason I mention this now is because I was informed he released a library (in the boost library incubator) that implements this stuff; you can find related documentation here. It seems the initial idea (that we both use here) and allowed code like this:

(Op<Max>(args) + ...); // Op is a function producing the custom fold type

was left out in favor of lazy evaluation and stateful operators (or not included yet, can't know for sure).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!