函数模板
Coddy 面向 Rust 开发者的 C++ 课程的第 25 课,共 48 课。
Rust 泛型使用 trait 约束来限定可用的行为。C++17 模板会在实例化时检查所需的操作,不需要 C++20 概念。C++ 模板会实例化带类型的代码。模板定义通常应放在头文件中,这样每个翻译单元都能实例化它们。
Rust
fn first<T>(values:&[T])->&T {&values[0]}
fn main(){
println!("{}",first(&["oak","elm"]));
}
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
template<class T>T twice(T value){return value+value;}
int main(){
std::cout<<twice(3)<<" "<<twice(std::string("ha"))<<"\n";
}
分别跟踪每个程序。这些示例使用与任务不同的操作或数据来演示这个概念,不假设源代码和目标代码的输出相同。
挑战
简单输入:两个整数。在头文件中为有序类型实现 smaller。返回较小的参数,包括独立测试中使用的字符串。
在 exercise.hpp 和 exercise.cpp 中实现已声明的 API。两个文件都可以编辑;请保留公开签名。锁定的 main.cpp 会读取标准输入并直接调用 API。它还会在指定情况下独立检查公开 API 的行为。在 API 中返回值,而不要打印。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
亲手试试
#include "exercise.hpp"
#include <iostream>
int main(){
{if(smaller(std::string("z"),std::string("a"))!="a")return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,b;in>>a>>b;std::cout<<smaller(a,b)<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Rust 开发者的 C++中的所有课
自己练习: C++ 在线编译器