🔴 手写三份和模板一份,结果一模一样
照顾这几样,要写几份
各写一份
写一份够
(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)上半段各写一份,下半段写一份:
#include <iostream>
#include <string>
/* 不用模板:同一件事对每种类型各写一遍 */
int twice_int(int x) { return x + x; }
double twice_double(double x) { return x + x; }
std::string twice_str(std::string x) { return x + x; }
/* 用模板:写一遍,三种类型都能用 */
template <typename T>
T twice(T x) { return x + x; }
int main() {
std::cout << twice_int(5) << "/" << twice_double(1.5) << "/"
<< twice_str("ab") << "/"
<< twice(5) << "/" << twice(1.5) << "/"
<< twice(std::string("ab")) << "\n";
return 0;
}
全部评论