C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Attribute [[discard]] and attributes on expressions

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Thu, 12 Oct 2023 09:23:18 -0400
On Thu, Oct 12, 2023 at 9:12 AM Sebastian Wittmeier via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Or
>
> template <typename... Args>
> void foo_other_platform([[maybe_unused]] Args... args)
> {
> }
>
> This (accidentally) copies the `Args`.
Also, after fixing that, this is exactly the `my::discard(Args&&...)`
function proposed by Bjorn Reese upthread, which Giuseppe said he didn't
care for. :)


> *Von:* Giuseppe D‘Angelo via Std-Proposals <std-proposals_at_[hidden]
> >
>
> On 12/10/2023 14:29, Bjorn Reese via Std-Proposals wrote:
> >> The purpose of [[discard]] is really for expressions, I don't see much
> >> value at discarding a pack as-is?
> > template <typename... Args>
> > void foo(Args... args)
> > {
> > #if SOME_PLATFORM
> > use(args...);
> > #else
> > discard(args...);
> > #endif
> > }
>
> But this can be spelled like this today, without discarding:
>
> > template <typename... Args>
> > void foo([[maybe_unused]] Args... args)
> > {
> > #if SOME_PLATFORM
> > use(args...);
> > #endif
> > }
>
> But that suppresses GCC's -Wunused-parameter diagnostic *even in the
SOME_PLATFORM branch*, which is usually unintended. The point of marking an
argument unused with (void)arg; is as a note to the reader: "Yes, I know I
didn't use this argument. That's on purpose." If you mark every argument as
[[maybe_unused]] at the top of the function, then you'll shut up the
*compiler* all right, but you aren't conveying any information to the human
reader about your intentions.
(Well, except that "maybe" you intend to ignore one or more of the
arguments. But the reader doesn't know what that "maybe" means.)

Consider

void foo(int x, int y) {
#if SOME_PLATFORM
    f(x,y);
#elif OTHER_PLATFORM
    g(x); h(x);
#else
    (void)x;
    (void)y;
#endif
}

versus

void foo([[maybe_unused]] int x, [[maybe_unused]] int y) {
#if SOME_PLATFORM
    f(x,y);
#elif OTHER_PLATFORM
    g(x); h(x);
#endif
}

The former rightly gives a -Wunused-parameter diagnostic when compiled for
OTHER_PLATFORM. The latter doesn't give the diagnostic, even though the
programmer probably wishes it would.

("But OP's example used a pack, and C++ doesn't let you index into a pack,
so it's never possible to use one element of a pack without using all the
elements! Your OTHER_PLATFORM example is impossible to write in C++ if x
and y are members of a pack!" Yes, but it might not *always* be impossible
to write. And we shouldn't design readability features around astronautical
bleeding-edge corner cases *as a general rule*.)

–Arthur

Received on 2023-10-12 13:23:32