C++ Logo

std-proposals

Advanced search

Re: Pack of functions - amendment to P1858

From: Fabio Alemagna <falemagn_at_[hidden]>
Date: Thu, 10 Sep 2020 15:52:17 +0200
Il giorno gio 10 set 2020 alle ore 15:20 Arthur O'Dwyer via Std-Proposals <
std-proposals_at_[hidden]> ha scritto:

> On Thu, Sep 10, 2020 at 5:30 AM Fabio Alemagna via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
>
>> I've been following the work on P1858
>> <http://open-std.org/JTC1/SC22/WG21/docs/papers/2020/p1858r2.html> and
>> just yesterday it occurred to me that it'd be useful to do something like
>> this:
>>
>> template <typename... Ts>
>>
>> struct Interface
>>
>> {
>>
>> rtype<Ts> func(ptype<Ts>) *...* = 0;
>>
>> };
>>
>>
>> template <typename... Ts>
>>
>> struct Implementation: Interface<Ts...>
>>
>> {
>>
>> rtype<Ts> func(ptype<Ts> p) override
>>
>> {
>>
>> return impl<Ts>(p);
>>
>> } *...*
>>
>> };
>>
>>
>> where rtype<>, ptype<> and impl<> are fictional templates with
>> exposition-only purpose.
>>
>
> Interesting idea, but it puts the '...' much too inconspicuously for my
> liking. The compiler would have to parse the entire function body before
> it'd be able to diagnose a missing '...' in the signature!
>

I thought of that, but then again the same "issue" exists for lambdas as
well.

template <typename... T>
std::any *test()
{
    static std::any array[] = {
        [](T){ /* possibly very long body */}...
    };

    return array;
}

It seems only consistent to me to allow method definition via pack
expansion just like lambda definition is allowed.

Besides, recursive templates aren't needed here. You could simulate what
> you seem to want by just doing
>
> template<class T>
> struct Interface {
> virtual rtype<T> func(ptype<T>) = 0;
> };
>
> template<class T>
> struct ImplDetail : Interface<T> {
> rtype<T> func(ptype<T> p) override { impl<T>(p); }
> };
>
> template<class... Ts>
> struct Implementation : ImplDetail<Ts>... {};
>
> This does involve one layer of indirection (the ImplDetail layer), but
> it's not recursive (not even in the colloquial sense of "recursive
> templates") and it's legal all the way back to C++11 IIRC.
>

Your example lacks the Interface<Ts...> type, which is what I need. It's
true one can avoid recursive inheritance, though: thanks to a redditor I
discovered that delegation to a sibling class is possible via virtual
inheritance, which I didn't know. However, virtual inheritance is still
more convoluted (and incurs space and time costs) than the pack expansion:
https://www.reddit.com/r/cpp/comments/iq08x3/pack_of_functions/g4nxcst?utm_source=share&utm_medium=web2x&context=3

Fabio

Received on 2020-09-10 08:56:02