C++模板的匹配规则----最特殊

来源:互联网 发布:单据打印软件 编辑:程序博客网 时间:2024/04/29 15:18

  C++模板技术让C++也能实现模板元编程,即在编译期间完成判断和计算。凡事总有特例,模板是为了匹配最一般的情况,但是针对特殊情况需要做优化,则需要特殊处理,这称为模板的特化。当模板特化后,一个调用可能会符合不同的模板,这样就需要选择正确的模板。C++中模板的匹配规则是:最特化匹配。下面是是示例程序:

#include <iostream>// General casetemplate<typename T0, typename T1, typename T2>struct S {  void id() { std::cout<<"General"<<std::endl;}};// Special case 1template<typename T0, typename T1>struct S<T0, T1, char> {  void id() { std::cout<<"Special case #1"<<std::endl;}};// Special case 2template<typename T0>struct S<T0, char, char> {  void id() {std::cout<<"Special case#2"<<std::endl;}};// Special case 3template<typename T>struct S<int, T, T> {  void id() {std::cout<<"Special case #3"<<std::endl;}};int main(int argc, char**argv) {  S<float, float, float>().id();  S<int, int, int>().id();  S<int, int, char>().id();  S<char, char, char>().id();  // S<int, char, char>().id(); /* compile error, can not decide which one is more special */  return EXIT_SUCCESS;}

  上述总共5组调用,其中第5组由于编译器无法决定模板的特殊性顺序,编译错误。

  1. S<float, float, float>匹配General case
  2. S<int, int, int>匹配Special case3
  3. S<int, int, char>匹配Special case1
  4. S<char, char, char>匹配Special case2

  本文完。

0 0