Idiomatic way to transfer caller name to template function

I have a templated function called from several other functions that must record the name of the function from which it was called. Ideally, I want to do something like the following:

template <typename T, const char* CALLER>
void foo(const T& arg) {
    // ...
}

However, this, of course, does not compile, since it CALLERis an invalid template parameter. Of course, I could just change the signature footo also take the string (caller name) to achieve this.

Question : Is there a preferred C ++ idiomatic way for this kind of thing?

+4
source share
1 answer

,

- ( , - ),

, , , , :

template<typename T>
void foo(T t, const char* func)
{
    std::cout << func << ": " << t << '\n';
}

foo const char*

void bar()
{
    foo(1, __func__); // callers responsibility to pass __func__
}

, foo , __func__ .

#define CALL_FOO(x) foo(x, __func__)

void bar()
{
    CALL_FOO(1);      // use the macro to pass __func__
}
+3

Source: https://habr.com/ru/post/1674515/


All Articles