C++ Logo

std-proposals

Advanced search

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

From: Pavel Vazharov <freakpv_at_[hidden]>
Date: Wed, 15 Nov 2023 14:08:49 +0200
>
> 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

Received on 2023-11-15 12:09:02