问题
Currently, one can use __PRETTY_FUNCTION__
to display a template type under gcc
, and clang
:
#include <iostream>
template <class T>
void print_type() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
int main(int argc, char* argv[]) {
print_type<const volatile int&>();
return 0;
}
Will output:
void print_type() [with T = const volatile int&]
With the reflection TS coming and reflection facilities in C++, I was wondering what the syntax would look like to be able to do something similar.
Note: as the reflection TS has not been voted in yet, I am only looking for a "probable" syntax.
回答1:
Guessing something like this:
template <class T>
void print_type() {
using F = reflexpr(print_type<T>);
std::cout << get_display_name_v<F> << std::endl;
}
You have to reflexpr
a specific thing, there's no way to get "this function I find myself in" - so that's print_type<T>
. And then the documentation just says that this is implementation defined.
If you want to write it all out, you can do:
template <class T>
void print_type() {
std::cout << "void "
<< get_name_v<reflexpr(print_type<T>)> // guaranteed "print_type"
<< "() [with T = "
<< get_display_name_v<reflexpr(T)>
<< "]" << std::endl;
}
It's unclear to me what get_name_v<reflexpr(const volatile int&)>
actually is. It seems like it's probably empty - T
is not a simple-type-specifier in this case) and there is no mention of cv- or ref-qualifiers, which is why I used get_display_name_v
.
Note that the Reflection TS is type-based - each reflexpr
gives you a type that you have to do type-based metaprogramming in. The approach the language itself will likely end up with is value-based reflection - that is reflexpr
yields a value of a small set of predefined reflection object types. This will make it easier to actually code, and is why we papers like constexpr!
and support for constexpr
allocation in the works.
来源:https://stackoverflow.com/questions/52461379/using-the-upcoming-c-reflection-facilities-to-print-the-full-name-of-a-type