面试题答案
一键面试#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;
}
在上述代码中:
- 主模板
IsIntegral
:定义了一个通用的模板IsIntegral
,其默认情况下value
为false
,表示非整数类型。 - 偏特化模板:针对各种整数类型(
char
、signed char
、unsigned char
、short
、unsigned short
、int
、unsigned int
、long
、unsigned long
、long long
、unsigned long long
)进行偏特化,将value
设置为true
,表示这些类型是整数类型。 - 封装常量表达式:通过
constexpr bool isIntegral_v = IsIntegral<T>::value;
提供了类似C++11标准库std::is_integral
的简洁使用方式。 main
函数:使用static_assert
进行编译期断言,验证isIntegral_v
是否按预期工作。
注意,C++标准库已经提供了 std::is_integral
用于判断一个类型是否为整数类型,实际开发中应优先使用标准库提供的功能。上述示例主要是为了展示如何手动实现类型萃取。