C++编程思想 第2卷 第5章 深入理解模板 有关函数模板的几个问题 函数模板重载

像普通函数一样
可以用相同的函数名重载函数模板
编译器在处理程序中的函数调用时
必须能够知道哪一个模板或普通函数是最适合调用的函数

//: C05:MinTest.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
#include <cstring>
#include <iostream>
using std::strcmp;
using std::cout;
using std::endl;

template<typename T> const T& min(const T& a, const T& b) {
  return (a < b) ? a : b;
}

const char* min(const char* a, const char* b) {
  return (strcmp(a, b) < 0) ? a : b;
}

double min(double x, double y) {
  return (x < y) ? x : y;
}

int main() {
  const char *s2 = "say \"Ni-!\"", *s1 = "knights who";
  cout << min(1, 2) << endl;      // 1: 1 (template)
  cout << min(1.0, 2.0) << endl;  // 2: 1 (double)
  cout << min(1, 2.0) << endl;    // 3: 1 (double)
  cout << min(s1, s2) << endl;    // 4: knights who (const
                                  //                 char*)
  cout << min<>(s1, s2) << endl;  // 5: say "Ni-!"
                                  //    (template)
  getchar();
} ///:~


输出
1
1
1
knights who
say "Ni-!"

除了函数模板
程序还定义了两个非模板函数
一个C语言风格的字符串版本
和一个double版本的min()函数

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/82084086