MST

星途 面试题库

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

请简述如何使用C++模板元编程实现一个类型萃取(Type Traits),用于判断一个类型是否是整数类型。请给出具体代码示例。
27.3万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <type_traits>

// 主模板
template <typename T>
struct IsIntegral {
    static const bool value = false;
};

// 偏特化模板,针对整数类型
template <>
struct IsIntegral<char> {
    static const bool value = true;
};

template <>
struct IsIntegral<signed char> {
    static const bool value = true;
};

template <>
struct IsIntegral<unsigned char> {
    static const bool value = true;
};

template <>
struct IsIntegral<short> {
    static const bool value = true;
};

template <>
struct IsIntegral<unsigned short> {
    static const bool value = true;
};

template <>
struct IsIntegral<int> {
    static const bool value = true;
};

template <>
struct IsIntegral<unsigned int> {
    static const bool value = true;
};

template <>
struct IsIntegral<long> {
    static const bool value = true;
};

template <>
struct IsIntegral<unsigned long> {
    static const bool value = true;
};

template <>
struct IsIntegral<long long> {
    static const bool value = true;
};

template <>
struct IsIntegral<unsigned long long> {
    static const bool value = true;
};

// C++11标准库风格的封装
template <typename T>
constexpr bool isIntegral_v = IsIntegral<T>::value;

int main() {
    static_assert(isIntegral_v<int> == true, "int should be integral");
    static_assert(isIntegral_v<double> == false, "double should not be integral");
    return 0;
}

在上述代码中:

  1. 主模板 IsIntegral:定义了一个通用的模板 IsIntegral,其默认情况下 valuefalse,表示非整数类型。
  2. 偏特化模板:针对各种整数类型(charsigned charunsigned charshortunsigned shortintunsigned intlongunsigned longlong longunsigned long long)进行偏特化,将 value 设置为 true,表示这些类型是整数类型。
  3. 封装常量表达式:通过 constexpr bool isIntegral_v = IsIntegral<T>::value; 提供了类似C++11标准库 std::is_integral 的简洁使用方式。
  4. main 函数:使用 static_assert 进行编译期断言,验证 isIntegral_v 是否按预期工作。

注意,C++标准库已经提供了 std::is_integral 用于判断一个类型是否为整数类型,实际开发中应优先使用标准库提供的功能。上述示例主要是为了展示如何手动实现类型萃取。