Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c++ - Fold expressions with arbitrary callable?

Looking over the C++17 paper on folds, (and on cppreference), I'm confused as to why the choice was made to only work with operators? At first glance it seems like it would make it easier to expand (... + args) by just shoving a + token between the elements of args, but I'm unconvinced this is a great decision.

Why can't a binary lambda expression work just as well and follow the same expansion as the latter above? It's jarring to me that a fold syntax would be added to a language without support for arbitrary callables, so does the syntax allow a way to use them that I'm just not seeing?


Update: This works for a variadic min() function with clang

template <typename T>
struct MinWrapper {
    const T& obj;
};

template <typename T, typename U, typename V=std::common_type_t<T,U>>
constexpr MinWrapper<V> operator%(
        const MinWrapper<T>& lhs, const MinWrapper<U>& rhs) {
    return {lhs.obj < rhs.obj ? lhs.obj : rhs.obj};
}


template <typename... Ts>
constexpr auto min(Ts&&... args) {
    return (MinWrapper<Ts>{args} % ...).obj;
}
question from:https://stackoverflow.com/questions/27582862/fold-expressions-with-arbitrary-callable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...