Menu
CoddyTech

函数模板

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

没有类型声明的 PHP 函数是一段在运行时处理所有参数的代码。它的 + 会对数字字符串进行算术运算,因此 "4" + "4" 的结果是 8;程序运行时遇到非数字字符串则会抛出 TypeError;拼接则使用另一个运算符 .。C++ 模板会实例化出具体类型的实现。C++ 模板会实例化出带类型的代码:twice(3) 会生成一个适用于 int 的版本,而 twice(std::string("ha")) 会生成一个适用于 std::string 的版本,其中 + 会进行拼接;如果某种类型没有可用的 +,就会在编译时失败。模板定义通常应放在头文件中,这样每个翻译单元都能实例化它们。

PHP

<?php
function twice($value) {
    return $value + $value;
}
echo twice(3), "\n";
echo twice("4"), "\n";
try {
    echo twice("ha"), "\n";
} catch (TypeError $e) {
    echo "TypeError\n";
}

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";
}

分别跟踪每个程序。这些示例使用与任务不同的操作或数据来说明这个概念,不假设源程序和目标程序的输出相同。

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自我测试

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

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

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