Menu
CoddyTech

函数模板

Coddy 面向 Lua 开发者的 C++ 课程的第 25 课,共 48 课。

Lua 是动态类型语言,所以一个函数本来就能接受任何值,只有在调用运行时才会发现类型错误。Lua 的 + 只能用于算术运算:它会把 "4" 这样的数字字符串转换为数字,并对 "ha" 抛出错误;连接字符串要使用 ..。C++ 函数模板是一种配方,编译器会针对它所使用的每种类型实例化一次,从而生成分别经过检查的代码,例如用于 int、double 和 std::string 的代码;+ 的含义取决于对应的类型。模板定义通常放在头文件中,因为每个使用该模板的文件都需要完整定义才能实例化它。

Lua

local function twice(value)
  return value + value
end
print(twice(3))
print(twice(1.5))
print(twice("4"))

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"))<<" "<<twice(1.5)<<"\n";
}

在 Lua 中,像 twice(true) 这样的调用会在运行时失败。在 C++ 中,任何不支持合适 + 运算符的类型,都会在模板实例化时被拒绝,程序甚至还没开始运行。

challenge icon

挑战

简单

输入:两个整数。在头文件中为有序类型实现 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";
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Lua 开发者的 C++中的所有课

自己练习: C++ 在线编译器