一份代码,管住两种类型
(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)
#include <iostream>
#include <string>
/* 一份代码,管住所有"能比大小"的类型 */
template <typename T>
const T &bigger(const T &a, const T &b) { return (a > b) ? a : b; }
template <typename T>
class Box {
public:
explicit Box(T v) : v_(std::move(v)) {}
const T &get() const { return v_; }
private:
T v_;
};
int main() {
Box<int> bi(7);
Box<std::string> bs("hi");
std::cout << bigger(3, 9) << "/"
<< bigger(std::string("apple"), std::string("pear")) << "/"
<< bi.get() << "/" << bs.get() << "\n";
return 0;
}
全部评论