欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > C++: 获取auto的实际类型

C++: 获取auto的实际类型

2025/6/25 11:00:48 来源:https://blog.csdn.net/baiyu33/article/details/147168006  浏览:    关键词:C++: 获取auto的实际类型
    auto a = "hello";auto* b = "hello";auto& c = "hello";

上述 a, b, c 类型分别是什么? 在不使用 IDE 提供的 inlay hints 情况下, 可以编译期获取,然后运行时打印出来:

方法:

  • 用 decltype(var) ,在编译期获取变量类型
  • 将这个类型作为模板函数的模板类型T
  • __PRETTY_FUNCTION__/__FUNCSIG__ 宏,打印函数名字

关键函数:

template<typename T>
void show_type() {
#ifdef __GNUC__std::cout << __PRETTY_FUNCTION__ << "\n";
#elif _MSC_VERstd::cout << __FUNCSIG__ << "\n";
#endif
}

调用:

    auto a = "hello";auto* b = "hello";auto& c = "hello";show_type<decltype(a)>();show_type<decltype(b)>();show_type<decltype(c)>();
}

完整代码:

https://godbolt.org/z/rKqajxP3W

#include <type_traits>
#include <iostream>
#include <string.h>template<typename T>
void show_type() {
#ifdef __GNUC__std::cout << __PRETTY_FUNCTION__ << "\n";
#elif _MSC_VERstd::cout << __FUNCSIG__ << "\n";
#endif
}int main()
{std::cout << std::boolalpha;// "Who goes with F\145rgus?\012" 的类型auto s = "Who goes with F\145rgus?\012";std::cout << strlen(s) << std::endl;std::cout << std::is_same<decltype("Who goes with F\145rgus?\012"), const char(&)[23]>::value << std::endl;show_type<decltype(s)>();show_type<decltype("Who goes with F\145rgus?\012")>();auto a = "hello";auto* b = "hello";auto& c = "hello";show_type<decltype(a)>();show_type<decltype(b)>();show_type<decltype(c)>();return 0;
}

Apple Clang 15.0.0:

2.7 git:(2.1) ✗ g++ main.cpp -std=c++11
➜  2.7 git:(2.1) ✗ ./a.out 
22
true
void show_type() [T = const char *]
void show_type() [T = const char (&)[23]]
void show_type() [T = const char *]
void show_type() [T = const char *]
void show_type() [T = const char (&)[6]]

MSVC :

22
true
void __cdecl show_type<const char*>(void)
void __cdecl show_type<const char(&)[23]>(void)
void __cdecl show_type<const char*>(void)
void __cdecl show_type<const char*>(void)
void __cdecl show_type<const char(&)[6]>(void)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词