由于来到有特殊背景的公司上班后,电脑无法访问外网,导致学习都停下来,为了敦促自己学习,周末进行复习和学习
- 函数模板,在编译时经过两个步骤:
-
- 模板内基本语法检查
-
- 模板实例化时对实参类型进行类型检查,对函数调用进行检查。其中模板类型和实参类型发生关联叫做演绎:
// 1. 模板内基本语法检查 templateT _sum(T const& a, T const& b) { if (true) { return a + b; // } // 即使函数模板这个实例没有被实例化,编译器在第一阶段也能发现该语法错误 } int main() { return 0; }
// 2. 模板参数类型检查 templateT _sum(T const& a, T const& b) { return a + b; } int main() { int32_t a = 1; int16_t b = 2; _sum(a, b); // error 对于类型T来说 int32_t 和int16_t不同 _sum(a, static_cast (b)); // 强制类型转换 _sum (a, b); // 显示指定T为int32_t,然后触发类型提升 _sum(int32_t(1), int32_t(2)) // 通过int32_t演绎出类型T // 检查函数调用 _sum(std::vector (1, 'a'), std::vector (2, 'b')); // error std::vector 没有定义operator+ _sum(std::string("hello"), std::string("world")); // std::string定义并实现了operator+ return 0; }
那么我就写一个定义operator+的类型抛砖引玉:
templateT _sum(T const& a, T const& b) { return a + b; } struct Integer { // 禁止隐式构造,如果不添加explicit就可以_sum (1, Integer(2)); 我要禁止这种行为 explicit Integer(int32_t a) : x_(a) {} // 成员函数使用const修饰,一方面我不寻求修改x_ // 另一方面当入参是 T *const this时,能找到本函数 比如T const*与T const&来引用对象时 Integer operator+(int32_t b) const { return Integer(x_ + b); } Integer operator+(Integer const &b) const { return Integer(x_ + b.x_); } // 本例x_是public的无需单独给下面函数做友元 // friend std::ostream &operator<<(std::ostream &, const Integer &); int32_t x_; }; std::ostream &operator<<(std::ostream &o, const Integer &i) { o << i.x_; return o; } int main() { auto c = _sum (1, Integer(2)); // error 必须显示构造 std::cout << _sum(Integer(1), Integer(2)) << std::endl; return {}; }
呕,前面提到演绎,下面再举个例子:
templateRtType _Sum_1(T const& a, T const& b) { return (a + b).x_; } template RtType _Sum_2(T const& a, T const& b, RtType) { return (a + b).x_; } int main() { auto a = _Sum_1 (Integer(1), Integer(2)); // 显式指定,入参类型相同,个数为2 auto b = _Sum_2(Integer(1), Integer(2), 2); // 通过第三个参数来演绎RtType,个数为3 return {}; }



