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)