MST

星途 面试题库

面试题:C++ 模板元编程之函数模板特化

请编写一个函数模板 `max`,用于返回两个参数中的较大值。然后,对 `max` 函数模板进行特化,使其可以处理 `std::string` 类型的参数,并比较字符串的长度来返回较长的字符串。
34.6万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <string>

// 函数模板,返回两个参数中的较大值
template<typename T>
T max(T a, T b) {
    return a > b? a : b;
}

// 函数模板特化,处理std::string类型参数
template<>
std::string max<std::string>(std::string a, std::string b) {
    return a.length() > b.length()? a : b;
}