面试题答案
一键面试#include <iostream>
#include <string>
#include <vector>
// 函数模板定义
template <typename T>
void printType(const T& value) {
std::cout << "通用版本: " << value << std::endl;
}
// std::string 类型的特化版本
template <>
void printType(const std::string& value) {
std::cout << "std::string 特化版本: " << value << std::endl;
}
// std::vector<int> 类型的偏特化版本
template <>
void printType(const std::vector<int>& value) {
std::cout << "std::vector<int> 偏特化版本: ";
for (int num : value) {
std::cout << num << " ";
}
std::cout << std::endl;
}
你可以使用以下方式调用这些函数:
int main() {
int num = 42;
std::string str = "Hello, World!";
std::vector<int> vec = {1, 2, 3, 4, 5};
printType(num);
printType(str);
printType(vec);
return 0;
}