MST

星途 面试题库

面试题:C++ 模板元编程中的类型萃取

请阐述在C++模板元编程中,如何使用类型萃取(Type Traits)来获取一个类型的属性,比如判断一个类型是否为指针类型?请给出具体的代码示例。
46.1万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

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

在上述代码中:

  1. 引入了<type_traits>头文件,该头文件提供了各种类型萃取的工具。
  2. std::is_pointer_v<T>是C++17引入的类型萃取工具,用于判断T是否为指针类型。如果T是指针类型,std::is_pointer_v<T>的值为true,否则为false
  3. if constexpr是C++17引入的编译期条件判断语句,使得在编译期就可以根据类型萃取的结果进行不同的处理。
  4. main函数中,分别对指针类型int*和非指针类型int调用了check_type函数进行类型判断。