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

缺少普通函数时
对函数模板进行重载有可能引起二义性的情况
即不知道选择哪个模板

//: C05:PartialOrder.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.
// Reveals ordering of function templates.
#include <iostream>
using namespace std;

template<class T> void f(T) {
  cout << "T" << endl;
}

template<class T> void f(T*) {
  cout << "T*" << endl;
}

template<class T> void f(const T*) {
  cout << "const T*" << endl;
}

int main() {
  f(0);            // T
  int i = 0;
  f(&i);           // T*
  const int j = 0;
  f(&j);           // const T*
  getchar();
} ///:~


输出
T
T*
const T*

f(&i)调用和第1个模板匹配
但由于第2个模板的特化传递更高
因此这里调用了第2个模板
在此处第3个模板不能被调用
因为该指针不是指向const的指针

猜你喜欢

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