// C++ 泛型编程示例:模板函数
#include <iostream>
#include <vector>
// 定义一个模板函数,可以接受任意类型的参数并返回该类型的值
template <typename T>
T get_value(T val) {
return val;
}
// 定义一个模板函数,用于打印容器中的元素
template <typename Container>
void print_container(const Container& container) {
for (const auto& elem : container) {
std::cout << elem << " ";
}
std::cout << std::endl;
}
int main() {
// 使用模板函数 get_value
int int_val = get_value(42);
double double_val = get_value(3.14);
std::cout << "Integer value: " << int_val << std::endl;
std::cout << "Double value: " << double_val << std::endl;
// 使用模板函数 print_container 打印不同类型的容器
std::vector<int> int_vector = {1, 2, 3, 4, 5};
std::vector<std::string> string_vector = {"hello", "world"};
std::cout << "Integer vector: ";
print_container(int_vector);
std::cout << "String vector: ";
print_container(string_vector);
return 0;
}
模板函数 get_value:
template <typename T> 表示这是一个模板函数,T 是一个占位符类型。T get_value(T val) 表示该函数接受一个类型为 T 的参数,并返回相同类型的值。模板函数 print_container:
template <typename Container> 表示这是一个模板函数,Container 是一个占位符类型。void print_container(const Container& container) 表示该函数接受一个容器类型的引用,并遍历容器中的元素进行打印。std::vector、std::list 等。main 函数:
get_value 和 print_container。get_value,以及如何传递不同类型的容器给 print_container。上一篇:c++ 静态类
下一篇:随机数c++
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站