使用即将推出的 C++ 反射工具打印类型的全名 [英] Using the upcoming C++ reflection facilities to print the full name of a type

查看:45
本文介绍了使用即将推出的 C++ 反射工具打印类型的全名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前可以使用__PRETTY_FUNCTION__gccclang下显示模板类型:

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;
}

将输出:

void print_type() [with T = const volatile int&]

随着 reflection TS 的到来和 C++ 中的反射设施,我被想知道能够执行类似操作的语法是什么样的.

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.

注意:由于反射 TS 还没有被投票,我只是在寻找一个可能的"语法.

Note: as the reflection TS has not been voted in yet, I am only looking for a "probable" syntax.

推荐答案

猜测是这样的:

template <class T>
void print_type() {
    using F = reflexpr(print_type<T>);
    std::cout << get_display_name_v<F> << std::endl;
}

你必须reflexpr一个特定的东西,没有办法得到我发现自己处于这个功能" - 所以那就是print_type.然后文档只是说这是实现定义的.

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;
}

我不清楚 get_name_v 实际上是什么.似乎它可能是空的 - T 在这种情况下不是 simple-type-specifier)并且没有提到 cv- 或 ref-限定符,这就是为什么我使用了 get_display_name_v.

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.

请注意,反射 TS 是基于类型的 - 每个 reflexpr 都为您提供一个类型,您必须在其中进行基于类型的元编程.语言本身最终可能采用的方法是 value-based 反射 - 即 reflexpr 产生一小组预定义反射对象类型的值.这将使实际编码更容易,这就是为什么我们在工作中喜欢 constexpr! 和支持 constexpr 分配的原因.

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.

这篇关于使用即将推出的 C++ 反射工具打印类型的全名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆