函数模板
Coddy 面向 Luau 开发者的 C++ 课程的第 25 课,共 48 课。
Luau 泛型函数和类型注解只供类型检查器使用:运行时,所有值都由同一个函数体处理,并且必须自行根据 type() 进行分支。C++ 模板会实例化出具体类型的实现。C++ 模板会实例化出类型化代码。模板定义通常应放在头文件中,这样每个翻译单元都可以实例化它们。
Luau
local function twice(value)
if type(value) == "string" then
return value .. value
end
return value + value
end
print(twice(3))
print(twice("ha"))
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";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Luau 开发者的 C++中的所有课
自己练习: C++ 在线编译器