面试题答案
一键面试SFINAE 解释
SFINAE(Substitution Failure Is Not An Error)是 C++ 模板元编程中的一种机制。当编译器在实例化模板时,如果在替换模板参数的过程中发生类型替换失败,编译器不会将其视为错误,而是继续寻找其他可行的模板重载,只有在找不到任何可行的模板重载时才会报错。
示例代码
#include <iostream>
#include <type_traits>
// 辅助模板类,用于判断类型是否为整数
template <typename T>
struct is_integer_type : std::false_type {};
template <>
struct is_integer_type<int> : std::true_type {};
// 处理整数类型的模板函数
template <typename T, typename = std::enable_if_t<is_integer_type<T>::value>>
void process(T num) {
std::cout << "Processing integer: " << num << std::endl;
}
// 处理浮点数类型的模板函数
template <typename T, typename = std::enable_if_t<!is_integer_type<T>::value && std::is_floating_point_v<T>>>
void process(T num) {
std::cout << "Processing floating - point: " << num << std::endl;
}
int main() {
int intValue = 10;
double doubleValue = 3.14;
process(intValue);
process(doubleValue);
return 0;
}
在上述代码中:
is_integer_type
是一个类型特征模板类,用于判断类型是否为int
。- 两个
process
模板函数使用std::enable_if_t
结合is_integer_type
来决定模板是否可行。 - 在
main
函数中,根据传入参数的类型,编译器会选择合适的process
函数实例化并调用。如果传入整数,调用处理整数的process
函数;如果传入浮点数,调用处理浮点数的process
函数。