In my infinite quest to push limits of what can be used as non type template parameter I was trying to see if I can use std::source_location
as non type template parameter.
That failed with a weird message, since I presume source_location is some magical struct...
type 'std::experimental::source_location' of non-type template parameter is not a structural type
It failed, so I tried to workaround that with using .file_name, but that also fails (godbolt).
note: candidate template ignored: substitution failure: pointer to subobject of string literal is not allowed in a template argument
#include<iostream>
#include<experimental/source_location>
template<auto src_loc = std::experimental::source_location::current().file_name()>
void log_first(){
static bool dummy =([]{
std::cout << "Logging first call" + src_loc << std::endl;
}(), false);
}
int main() {
log_first();
log_first();
}
Is there any way to make this work without use of macros?
To be clear I am asking about using source_location
as template parameter, not about solving my toy example, it is just here to demonstrate potential use case.
std::source_location
is specified as:And the rules for the kinds of types that can be used as non-template template parameters require that a type be structural, which means, from [temp.param]/7, emphasis mine:
source_location
does not have all of its non-static data members public, so it is not structural, so it is not usable as a non-type template parameter.This part:
does not work because of [temp.arg.nontype]/3:
But what you can do is create your own type, that is structural, that is constructible from
source_location
. It's just that the strings can't bechar const*
, they have to own the data. If you look in the examples in P0732, we can build up:That might be awkward to deal with in this case, so you could also just pick some reasonable max size and go with that.