Fold expressions with arbitrary callable?

前端 未结 2 999
春和景丽
春和景丽 2021-01-01 09:00

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 woul

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 09:32

    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
    struct wp {
        T const& val; 
        // yes there should be constructors
    };
    

    2. Machinery to transform packs to wrapped packs

    template
    using wrapped_pack = make_wrapped
    

    3. Overload a built in operator for wp

    template
    ret_val operator+(wp const& lhs, wp 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 callable 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).

提交回复
热议问题