C++编程思想 第2卷 第5章 深入理解模板 模板特化 显示特化

编程人员可以自己为一个模板提供代码使其特化
类模板经常需要程序员为它提供模板特化
 

//: C05:MinTest2.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<class T> const T& min(const T& a, const T& b) {
  return (a < b) ? a : b;
}

// An explicit specialization of the min template
template<>
const char* const& min<const char*>(const char* const& a,
                                    const char* const& b) {
  return (strcmp(a, b) < 0) ? a : b;
}

int main() {
  const char *s2 = "say \"Ni-!\"", *s1 = "knights who";
  cout << min(s1, s2) << endl;
  cout << min<>(s1, s2) << endl;
  getchar();
} ///:~

输出
knights who
knights who

前缀 template <>  
告诉编译器接下来的是一个模板的特化
模板特化的类型必须出现在函数名后紧跟的尖括号中
就像通常在一个明确指定场所类型的函数调用中一样
 

猜你喜欢

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