C++ Logo

std-proposals

Advanced search

Re: Meta types

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Tue, 4 Feb 2020 10:16:17 -0500
On Tue, Feb 4, 2020 at 8:16 AM Михаил Найденов via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> This definitely steps into both "language variant" and Pattern Matching
> territory.
> I am not sure what optimization we can expect from "language variant", but
> PM should give us close to your ideal code
>
> void main(int argc, char const* const* argv){
> inspect(halve(args))
> Numeric x => std::cout << "You passed 2*(" << x << ") arguments\n";
> return 0;
> }
>

The current Pattern Matching proposal doesn't give the programmer any way
to write `halve` so that it can actually return either of two alternative
types (`unsigned` or `double`) depending on a *runtime* condition (the
evenness of the runtime argument).

However, I don't see anything wrong with the existing C++14 language
solution to OP's problem. It's not worth pursuing any crazy core-language
gymnastics unless you can provide a use-case that isn't already solvable
idiomatically in C++14 (17, 20). Here's the '14 solution:

template<class F>
void halve(unsigned i, const F& f) {
    if (i % 2 == 0) {
        f(i / 2);
    } else {
        f(i * 0.5);
    }
}

int main(int argc, char**) {
    halve(argc, [](auto x) {
        std::cout << "You passed 2*(" << x << ") arguments\n";
    });
    return 0;
}

Short, readable, relatively easy to understand. Certainly easi*er* to
understand than anything proposed in the OP.

–Arthur

Received on 2020-02-04 09:19:05