Why I can't pass this pointer as a template argument:
template <const char* T>
struct MyStruct
{};
int main()
{
static constexpr const char* func_name = nullptr;
MyStruct<func_name>{}; // Works
static constexpr const char* func_name2 = __func__;
MyStruct<func_name2>{};
// A template argument may not reference a non-external entity
// MyStruct: invalid expression as a template argument for 'T'
//error: the address of ‘__func__’ is not a valid template argument
}
I want to pass the name of the function as a template argument, and no workaround seems possible. Why?
According to the GCC documentation:
The identifier
__func__
is implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declarationstatic const char __func__[] = "function-name";
So it's as if it's declaring that inside the function, then I assign my constexpr const char*
to it, and then pass it as the template argument. That should work, does it not?
I know that there are gotchas when it comes to const char*
as a template argument. Before I was having trouble with passing a string literal (they're not allowed as template arguments). But in this case it seems I'm passing the address of a static array, which is a valid argument, no?