C++ Logo

std-proposals

Advanced search

[std-proposals] Callsite passed as template parameter

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Wed, 15 Nov 2023 11:58:57 +0000
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".

The above code would behave the same way as the below C++23 code:

#include <utility> // integer_sequence

#define QUOTEx(x) #x
#define QUOTE(x) QUOTEx(x)
#define TOKEN_PASTEx(x, y) x ## y
#define TOKEN_PASTE(x, y) TOKEN_PASTEx(x, y)

template <typename T, T... chars>
constexpr std::integer_sequence<T, chars...> operator""_cs() { return {}; }

#define callsite decltype( TOKEN_PASTE(__FILE__ "_Line_"
QUOTE(__LINE__) "_No_" QUOTE(__COUNTER__),_cs) )

struct TesterClass {
    inline static unsigned counter = 0u;
    TesterClass(void) { ++counter; }
};

template<typename T>
void Func(void)
{
    static TesterClass one_for_every_callsite;
}

#include <iostream> // cout, endl

int main(void)
{
    Func<callsite>();
    for ( unsigned i = 0u; i < 8u; ++i ) Func<callsite>();
    Func<callsite>();
    std::cout << "Count: " << TesterClass::counter << std::endl;
}

This would be very useful for data logging, or for implementing
functions that work along the same lines as 'strtok'.

Received on 2023-11-15 11:59:10