面试题答案
一键面试在C++中,可以使用<type_traits>
头文件来进行类型萃取。以下是判断一个类型是否为指针类型的代码示例:
#include <iostream>
#include <type_traits>
template <typename T>
void check_type() {
if constexpr (std::is_pointer_v<T>) {
std::cout << "T is a pointer type." << std::endl;
} else {
std::cout << "T is not a pointer type." << std::endl;
}
}
int main() {
int* ptr;
int num;
check_type<int*>();
check_type<int>();
return 0;
}
在上述代码中:
- 引入了
<type_traits>
头文件,该头文件提供了各种类型萃取的工具。 std::is_pointer_v<T>
是C++17引入的类型萃取工具,用于判断T
是否为指针类型。如果T
是指针类型,std::is_pointer_v<T>
的值为true
,否则为false
。if constexpr
是C++17引入的编译期条件判断语句,使得在编译期就可以根据类型萃取的结果进行不同的处理。- 在
main
函数中,分别对指针类型int*
和非指针类型int
调用了check_type
函数进行类型判断。