MST
星途 面试题库

面试题:C++ 函数模板的特化与偏特化

请编写一个函数模板 `printType`,用于打印不同类型的变量值。然后,针对 `std::string` 类型编写一个特化版本,针对 `std::vector<int>` 类型编写一个偏特化版本,展示如何在C++中实现函数模板的特化与偏特化。
50.3万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#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;
}