C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Callsite passed as template parameter

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Wed, 15 Nov 2023 14:30:37 -0500
On Wed, Nov 15, 2023 at 2:29 PM Lénárd Szolnoki via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Hi,
>
> On 15 November 2023 12:08:49 GMT, Pavel Vazharov via Std-Proposals <std-proposals_at_[hidden]> wrote:
> >>
> >> Let's say we have a function as follows:
> >>
> >> void Func(void)
> >> {
> >> static int one_for_each_callsite = 0;
> >> }
> >>
> >> We want this function to have a unique static-duration variable for
> >> each place in the code that this function is called. It would be cool
> >> if we could just write the following:
> >>
> >> template<callsite>
> >> void Func(void)
> >> {
> >> static int one_for_each_callsite = 0;
> >> }
> >>
> >> And so then we could call this function from a few different places:
> >>
> >> int main(void)
> >> {
> >> Func(); // This is the 1st call site
> >>
> >> while ( Something() ) Func(); // This is the 2nd call site
> >>
> >> Func(); // This is the 3rd call site
> >> }
> >>
> >> So the above code would have three copies of the variable
> >> "one_for_each_callsite".
> >>
> >> If I understood you correctly, you can achieve this today pretty easily
> >
> >#include <cstdio>
> >
> >template <typename Tag = decltype([]{})>
> >void fun()
> >{
> > static int counter = 0;
> > std::printf("addr:%p value:%i\n", &counter, counter);
> >}
> >
> >int main()
> >{
> > fun();
> > fun();
> > fun();
> >
> > return 0;
> >}
> >
> >This prints something like <https://godbolt.org/z/9Mh8Ea6P8>
> >
> >addr:0x40401c value:0
> >addr:0x404020 value:0
> >addr:0x404024 value:0
>
> Isn't this a major ODR-violation footgun?

Footgun? Yes. ODR violation? No.

Received on 2023-11-15 19:30:50