以下是一个在模板中定义函数的例子:

#include <iostream>
#include <vector>
#include <string>

template<typename T>
void print_vector(std::vector<T>& vec) {
    for (const auto& item : vec) {
        std::cout << item << " ";
    }
    std::cout << std::endl;
}

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5};
    std::vector<std::string> words = {"hello", "world", "template"};

    print_vector(nums);
    print_vector(words);

    return 0;
}

在这个例子中,我们定义了一个名为 print_vector 的函数模板,它接受一个类型为 Tstd::vector 引用,并打印其所有元素。在 main 函数中,我们分别传入了一个包含整数和字符串的 std::vector,并调用了 print_vector 函数模板来打印它们的所有元素。

给我一个在模板中定义函数的例子

原文地址: https://www.cveoy.top/t/topic/bzex 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录