请选择 进入手机版 | 继续访问电脑版

C++模板元编程(C++ template metaprogramming)(3)

发表于 2023-1-21 20:54:48 显示全部楼层 0 14000

关于 template、typename、this 关键字的使用(文献[4]模板,文献[5]):

  • 依赖于模板参数(template parameter,形式参数,实参英文为 argument)的名字被称为依赖名字(dependent name),C++标准规定,如果解析器在一个模板中遇到一个嵌套依赖名字,它假定那个名字不是一个类型,除非显式用 typename 关键字前置修饰该名字;
  • 和上一条 typename 用法类似,template 用于指明嵌套类型或函数为模板;
  • this 用于指定查找基类中的成员(当基类是依赖模板参数的类模板实例时,由于实例化总是推迟,这时不依赖模板参数的名字不在基类中查找,文献[1]第 166 页)。


一个例子如下(需要 GCC 编译,GCC 对 C++11 几乎全面支持,VS2013 此处总是在基类中查找名字,且函数模板前不需要 template):
  1. #include <iostream>

  2. template<typename T>
  3. class aTMP{
  4.     public: typedef const T reType;
  5. };

  6. void f() { std::cout << "global f()\n"; }

  7. template<typename T>
  8. class Base {
  9.     public:
  10.         template <int N = 99>
  11.         void f() { std::cout << "member f(): " << N << '\n'; }
  12. };

  13. template<typename T>
  14. class Derived : public Base<T> {

复制代码
  1. global f()
  2. member f(): 99
  3. member f(): 22
  4. global f()
复制代码
C++11 关于模板的新特性(详见文献[1]第15章,文献[4]C++11):

  • “>>” 根据上下文自动识别正确语义;
  • 函数模板参数默认值;
  • 变长模板参数(扩展 sizeof...() 获取参数个数);
  • 模板别名(扩展 using 关键字);
  • 外部模板实例(拓展 extern 关键字),弃用 export template。


在本文中,如无特别声明将不使用 C++11 的特性(除了 “>>”)。


2. 模板元编程概述

如果对 C++ 模板不熟悉(光熟悉语法还不算熟悉),可以先跳过本节,往下看完例子再回来。

C++ 模板最初是为实现泛型编程设计的,但人们发现模板的能力远远不止于那些设计的功能。
一个重要的理论结论就是:C++ 模板是图灵完备的(Turing-complete),其证明过程请见文献[8](就是用 C++ 模板模拟图灵机),
理论上说 C++ 模板可以执行任何计算任务,但实际上因为模板是编译期计算,其能力受到具体编译器实现的限制(如递归嵌套深度,C++11 要求至少 1024,C++98 要求至少 17)。
C++ 模板元编程是“意外”功能,而不是设计的功能,这也是 C++ 模板元编程语法丑陋的根源。

C++ 模板是图灵完备的,这使得 C++ 成为两层次语言(two-level languages,中文暂且这么翻译,文献[9]),
其中,执行编译计算的代码称为静态代码(static code),执行运行期计算的代码称为动态代码(dynamic code),
C++ 的静态代码由模板实现(预处理的宏也算是能进行部分静态计算吧,也就是能进行部分元编程,称为宏元编程,见 Boost 元编程库即 BCCL,文献[16]和文献[1] 10.4)。

具体来说 C++ 模板可以做以下事情:编译期数值计算、类型计算、代码计算(如循环展开),
其中数值计算实际不太有意义,而类型计算和代码计算可以使得代码更加通用,更加易用,性能更好(也更难阅读,更难调试,有时也会有代码膨胀问题)。
编译期计算在编译过程中的位置请见下图(取自文献[10]),可以看到关键是模板的机制在编译具体代码(模板实例)前执行:

C++ 模板元编程

从编程范型(programming paradigm)上来说,C++ 模板是函数式编程(functional programming),
它的主要特点是:函数调用不产生任何副作用(没有可变的存储),用递归形式实现循环结构的功能。
C++ 模板的特例化提供了条件判断能力,而模板递归嵌套提供了循环的能力,这两点使得其具有和普通语言一样通用的能力(图灵完备性)。

从编程形式来看,模板的“<>”中的模板参数相当于函数调用的输入参数,模板中的 typedef 或 static const 或 enum 定义函数返回值(类型或数值,数值仅支持整型,如果需要可以通过编码计算浮点数),
代码计算是通过类型计算进而选择类型的函数实现的(C++ 属于静态类型语言,编译器对类型的操控能力很强)。
代码示意如下:


  1. #include <iostream>

  2. template<typename T, int i=1>
  3. class someComputing {
  4. public:
  5.     typedef volatile T* retType; // 类型计算
  6.     enum { retValume = i + someComputing<T, i-1>::retValume }; // 数值计算,递归
  7.     static void f() { std::cout << "someComputing: i=" << i << '\n'; }
  8. };
  9. template<typename T> // 模板特例,递归终止条件
  10. class someComputing<T, 0> {
  11. public:
  12.     enum { retValume = 0 };
  13. };

  14. template<typename T>
  15. class codeComputing {
  16. public:
  17.     static void f() { T::f(); } // 根据类型调用函数,代码计算
  18. };

  19. int main(){
  20.     someComputing<int>::retType a=0;
  21.     std::cout << sizeof(a) << '\n'; // 64-bit 程序指针
  22.     // VS2013 默认最大递归深度500,GCC4.8 默认最大递归深度900(-ftemplate-depth=n)
  23.     std::cout << someComputing<int, 500>::retValume << '\n'; // 1+2+...+500
  24.     codeComputing<someComputing<int, 99>>::f();
  25.     std::cin.get(); return 0;
  26. }
复制代码


  1. 8
  2. 125250
  3. someComputing: i=99
复制代码


C++ 模板元编程概览框图如下(取自文献[9]):
模板元概览.png

下面我们将对图中的每个框进行深入讨论。



3. 编译期数值计算

第一个 C++ 模板元程序是 Erwin Unruh 在 1994 年写的(文献[14]),这个程序计算小于给定数 N 的全部素数(又叫质数),
程序并不运行(都不能通过编译),而是让编译器在错误信息中显示结果(直观展现了是编译期计算结果,C++ 模板元编程不是设计的功能,更像是在戏弄编译器,当然 C++11 有所改变),
由于年代久远,原来的程序用现在的编译器已经不能编译了,下面的代码在原来程序基础上稍作了修改(GCC 4.8 下使用 -fpermissvie,只显示警告信息):


  1. // Prime number computation by Erwin Unruh
  2. template<int i> struct D { D(void*); operator int(); }; // 构造函数参数为 void* 指针

  3. template<int p, int i> struct is_prime { // 判断 p 是否为素数,即 p 不能整除 2...p-1
  4.     enum { prim = (p%i) && is_prime<(i>2?p:0), i-1>::prim };
  5. };
  6. template<> struct is_prime<0, 0> { enum { prim = 1 }; };
  7. template<> struct is_prime<0, 1> { enum { prim = 1 }; };

  8. template<int i> struct Prime_print {
  9.     Prime_print<i-1> a;
  10.     enum { prim = is_prime<i, i-1>::prim };
  11.     // prim 为真时, prim?1:0 为 1,int 到 D<i> 转换报错;假时, 0 为 NULL 指针不报错
  12.     void f() { D<i> d = prim?1:0; a.f(); } // 调用 a.f() 实例化 Prime_print<i-1>::f()
  13. };
  14. template<> struct Prime_print<2> { // 特例,递归终止
  15.     enum { prim = 1 };
  16.     void f() { D<2> d = prim?1:0; }
  17. };

  18. #ifndef LAST
  19. #define LAST 10
  20. #endif

  21. int main() {
  22.     Prime_print<LAST> a; a.f(); // 必须调用 a.f() 以实例化 Prime_print<LAST>::f()
  23. }
复制代码


  1. sh-4.2# g++ -std=c++11 -fpermissive -o main *.cpp
  2. main.cpp: In member function 'void Prime_print<2>::f()':
  3. main.cpp:17:33: warning: invalid conversion from 'int' to 'void*' [-fpermissive]
  4.   void f() { D<2> d = prim ? 1 : 0; }
  5.                                  ^
  6. main.cpp:2:28: warning:   initializing argument 1 of 'D<i>::D(void*) [with int i = 2]' [-fpermissive]
  7. template<int i> struct D { D(void*); operator int(); };
  8.                             ^
  9. main.cpp: In instantiation of 'void Prime_print<i>::f() [with int i = 7]':
  10. main.cpp:13:36:   recursively required from 'void Prime_print<i>::f() [with int i = 9]'
  11. main.cpp:13:36:   required from 'void Prime_print<i>::f() [with int i = 10]'
  12. main.cpp:25:27:   required from here
  13. main.cpp:13:33: warning: invalid conversion from 'int' to 'void*' [-fpermissive]
  14.   void f() { D<i> d = prim ? 1 : 0; a.f(); }
  15.                                  ^
  16. main.cpp:2:28: warning:   initializing argument 1 of 'D<i>::D(void*) [with int i = 7]' [-fpermissive]
  17. template<int i> struct D { D(void*); operator int(); };
  18.                             ^
  19. main.cpp: In instantiation of 'void Prime_print<i>::f() [with int i = 5]':
  20. main.cpp:13:36:   recursively required from 'void Prime_print<i>::f() [with int i = 9]'
  21. main.cpp:13:36:   required from 'void Prime_print<i>::f() [with int i = 10]'
  22. main.cpp:25:27:   required from here
  23. main.cpp:13:33: warning: invalid conversion from 'int' to 'void*' [-fpermissive]
  24.   void f() { D<i> d = prim ? 1 : 0; a.f(); }
  25.                                  ^
  26. main.cpp:2:28: warning:   initializing argument 1 of 'D<i>::D(void*) [with int i = 5]' [-fpermissive]
  27. template<int i> struct D { D(void*); operator int(); };
  28.                             ^
  29. main.cpp: In instantiation of 'void Prime_print<i>::f() [with int i = 3]':
  30. main.cpp:13:36:   recursively required from 'void Prime_print<i>::f() [with int i = 9]'
  31. main.cpp:13:36:   required from 'void Prime_print<i>::f() [with int i = 10]'
  32. main.cpp:25:27:   required from here
  33. main.cpp:13:33: warning: invalid conversion from 'int' to 'void*' [-fpermissive]
  34.   void f() { D<i> d = prim ? 1 : 0; a.f(); }
  35.                                  ^
  36. main.cpp:2:28: warning:   initializing argument 1 of 'D<i>::D(void*) [with int i = 3]' [-fpermissive]
  37. template<int i> struct D { D(void*); operator int(); };
  38.                             ^
复制代码


上面的编译输出信息只给出了前一部分,虽然信息很杂,但还是可以看到其中有 10 以内全部素数:2、3、5、7。

到目前为止,虽然已经看到了阶乘、求和等递归数值计算,但都没涉及原理,下面以求和为例讲解 C++ 模板编译期数值计算的原理:



  1. #include <iostream>

  2. template<int N>
  3. class sumt{
  4. public: static const int ret = sumt<N-1>::ret + N;
  5. };
  6. template<>
  7. class sumt<0>{
  8. public: static const int ret = 0;
  9. };

  10. int main() {
  11.     std::cout << sumt<5>::ret << '\n';
  12.     std::cin.get(); return 0;
  13. }
复制代码

  1. 15
复制代码


当编译器遇到 sumt<5> 时,试图实例化之,sumt<5> 引用了 sumt<5-1> 即 sumt<4>,试图实例化 sumt<4>,
以此类推,直到 sumt<0>,sumt<0> 匹配模板特例,sumt<0>::ret 为 0,sumt<1>::ret 为 sumt<0>::ret+1 为 1,
以此类推,sumt<5>::ret 为 15。值得一提的是,
虽然对用户来说程序只是输出了一个编译期常量 sumt<5>::ret,
但在背后,编译器其实至少处理了 sumt<0> 到 sumt<5> 共 6 个类型。

从这个例子我们也可以窥探 C++ 模板元编程的函数式编程范型,
对比结构化求和程序:for(i=0,sum=0; i<=N; ++i) sum+=i; 用逐步改变存储(即变量 sum)的方式来对计算过程进行编程,
模板元程序没有可变的存储(都是编译期常量,是不可变的变量),
要表达求和过程就要用很多个常量:sumt<0>::ret,sumt<1>::ret,...,sumt<5>::ret 。

函数式编程看上去似乎效率低下(因为它和数学接近,而不是和硬件工作方式接近),
但有自己的优势:描述问题更加简洁清晰(前提是熟悉这种方式),没有可变的变量就没有数据依赖,方便进行并行化。



4. 模板下的控制结构

模板实现的条件 if 和 while 语句如下(文献[9]):


  1. // 通例为空,若不匹配特例将报错,很好的调试手段(这里是 bool 就无所谓了)
  2. template<bool c, typename Then, typename Else> class IF_ { };
  3. template<typename Then, typename Else>
  4. class IF_<true, Then, Else> { public: typedef Then reType; };
  5. template<typename Then, typename Else>
  6. class IF_<false,Then, Else> { public: typedef Else reType; };

  7. // 隐含要求: Condition 返回值 ret,Statement 有类型 Next
  8. template<template<typename> class Condition, typename Statement>
  9. class WHILE_ {
  10.     template<typename Statement> class STOP { public: typedef Statement reType; };
  11. public:
  12.     typedef typename
  13.         IF_<Condition<Statement>::ret,
  14.         WHILE_<Condition, typename Statement::Next>,
  15.         STOP<Statement>>::reType::reType
  16.     reType;
  17. };
复制代码


IF_<> 的使用示例见下面:


  1. const int len = 4;
  2. typedef
  3.     IF_<sizeof(short)==len, short,
  4.     IF_<sizeof(int)==len, int,
  5.     IF_<sizeof(long)==len, long,
  6.     IF_<sizeof(long long)==len, long long,
  7.     void>::reType>::reType>::reType>::reType
  8. int_my; // 定义一个指定字节数的类型
  9. std::cout << sizeof(int_my) << '\n';
复制代码


  1. 4
复制代码


WHILE_<> 的使用示例见下面:


  1. // 计算 1^e+2^e+...+n^e
  2. template<int n, int e>
  3. class sum_pow {
  4.     template<int i, int e> class pow_e{ public: enum{ ret=i*pow_e<i,e-1>::ret }; };
  5.     template<int i> class pow_e<i,0>{ public: enum{ ret=1 }; };
  6.     // 计算 i^e,嵌套类使得能够定义嵌套模板元函数,private 访问控制隐藏实现细节
  7.     template<int i> class pow{ public: enum{ ret=pow_e<i,e>::ret }; };
  8.     template<typename stat>
  9.     class cond { public: enum{ ret=(stat::ri<=n) }; };
  10.     template<int i, int sum>
  11.     class stat { public: typedef stat<i+1, sum+pow<i>::ret> Next;
  12.                          enum{ ri=i, ret=sum }; };
  13. public:
  14.     enum{ ret = WHILE_<cond, stat<1,0>>::reType::ret };
  15. };

  16. int main() {
  17.     std::cout << sum_pow<10, 2>::ret << '\n';
  18.     std::cin.get(); return 0;
  19. }
复制代码

  1. 385
复制代码


为了展现编译期数值计算的强大能力,下面是一个更复杂的计算:最大公约数(Greatest Common Divisor,GCD)和最小公倍数(Lowest Common Multiple,LCM),
经典的辗转相除算法:


  1. // 最小公倍数,普通函数
  2. int lcm(int a, int b){
  3.     int r, lcm=a*b;
  4.     while(r=a%b) { a = b; b = r; } // 因为用可变的存储,不能写成 a=b; b=a%b;
  5.     return lcm/b;
  6. }
  7. // 递归函数版本
  8. int gcd_r(int a, int b) { return b==0 ? a : gcd_r(b, a%b); } // 简洁
  9. int lcm_r(int a, int b) { return a * b / gcd_r(a,b); }

  10. // 模板版本
  11. template<int a, int b>
  12. class lcm_T{
  13.     template<typename stat>
  14.     class cond { public: enum{ ret=(stat::div!=0) }; };
  15.     template<int a, int b>
  16.     class stat { public: typedef stat<b, a%b> Next; enum{ div=a%b, ret=b }; };
  17.     static const int gcd = WHILE_<cond, stat<a,b>>::reType::ret;
  18. public:
  19.     static const int ret = a * b / gcd;
  20. };
  21. // 递归模板版本
  22. template<int a, int b>
  23. class lcm_T_r{
  24.     template<int a, int b> class gcd { public: enum{ ret = gcd<b,a%b>::ret }; };
  25.     template<int a> class gcd<a, 0> { public: enum{ ret = a }; };
  26. public:
  27.     static const int ret = a * b / gcd<a,b>::ret;
  28. };

  29. int main() {
  30.     std::cout << lcm(100, 36) << '\n';
  31.     std::cout << lcm_r(100, 36) << '\n';
  32.     std::cout << lcm_T<100, 36>::ret << '\n';
  33.     std::cout << lcm_T_r<100, 36>::ret << '\n';
  34.     std::cin.get(); return 0;
  35. }
复制代码

  1. 900
  2. 900
  3. 900
  4. 900
复制代码


上面例子中,定义一个类的整型常量,可以用 enum,也可以用 static const int,需要注意的是 enum 定义的常量的字节数不会超过 sizeof(int) (文献[2])。



5. 循环展开

文献[11]展示了一个循环展开(loop unrolling)的例子 -- 冒泡排序:


  1. #include <utility>  // std::swap

  2. // dynamic code, 普通函数版本
  3. void bubbleSort(int* data, int n)
  4. {
  5.     for(int i=n-1; i>0; --i) {
  6.         for(int j=0; j<i; ++j)
  7.             if (data[j]>data[j+1]) std::swap(data[j], data[j+1]);
  8.     }
  9. }
  10. // 数据长度为 4 时,手动循环展开
  11. inline void bubbleSort4(int* data)
  12. {
  13. #define COMP_SWAP(i, j) if(data[i]>data[j]) std::swap(data[i], data[j])
  14.     COMP_SWAP(0, 1); COMP_SWAP(1, 2); COMP_SWAP(2, 3);
  15.     COMP_SWAP(0, 1); COMP_SWAP(1, 2);
  16.     COMP_SWAP(0, 1);
  17. }

  18. // 递归函数版本,指导模板思路,最后一个参数是哑参数(dummy parameter),仅为分辨重载函数
  19. class recursion { };
  20. void bubbleSort(int* data, int n, recursion)
  21. {
  22.     if(n<=1) return;
  23.     for(int j=0; j<n-1; ++j) if(data[j]>data[j+1]) std::swap(data[j], data[j+1]);
  24.     bubbleSort(data, n-1, recursion());
  25. }

  26. // static code, 模板元编程版本
  27. template<int i, int j>
  28. inline void IntSwap(int* data) { // 比较和交换两个相邻元素
  29.     if(data[i]>data[j]) std::swap(data[i], data[j]);
  30. }

  31. template<int i, int j>
  32. inline void IntBubbleSortLoop(int* data) { // 一次冒泡,将前 i 个元素中最大的置换到最后
  33.     IntSwap<j, j+1>(data);
  34.     IntBubbleSortLoop<j<i-1?i:0, j<i-1?(j+1):0>(data);
  35. }
  36. template<>
  37. inline void IntBubbleSortLoop<0, 0>(int*) { }

  38. template<int n>
  39. inline void IntBubbleSort(int* data) { // 模板冒泡排序循环展开
  40.     IntBubbleSortLoop<n-1, 0>(data);
  41.     IntBubbleSort<n-1>(data);
  42. }
  43. template<>
  44. inline void IntBubbleSort<1>(int* data) { }
  45. 对循环次数固定且比较小的循环语句,对其进行展开并内联可以避免函数调用以及执行循环语句中的分支,从而可以提高性能,对上述代码做如下测试,代码在 VS2013 的 Release 下编译运行:

  46. #include <iostream>
  47. #include <omp.h>
  48. #include <string.h> // memcpy

  49. int main() {
  50.     double t1, t2, t3; const int num=100000000;
  51.     int data[4]; int inidata[4]={3,4,2,1};
  52.     t1 = omp_get_wtime();
  53.     for(int i=0; i<num; ++i) { memcpy(data, inidata, 4); bubbleSort(data, 4); }
  54.     t1 = omp_get_wtime()-t1;
  55.     t2 = omp_get_wtime();
  56.     for(int i=0; i<num; ++i) { memcpy(data, inidata, 4); bubbleSort4(data); }
  57.     t2 = omp_get_wtime()-t2;
  58.     t3 = omp_get_wtime();
  59.     for(int i=0; i<num; ++i) { memcpy(data, inidata, 4); IntBubbleSort<4>(data); }
  60.     t3 = omp_get_wtime()-t3;
  61.     std::cout << t1/t3 << '\t' << t2/t3 << '\n';
  62.     std::cin.get(); return 0;
  63. }
复制代码

  1. 2.38643 0.926521
复制代码


上述结果表明,模板元编程实现的循环展开能够达到和手动循环展开相近的性能(90% 以上),
并且性能是循环版本的 2 倍多(如果扣除 memcpy 函数占据的部分加速比将更高,根据 Amdahl 定律)。
这里可能有人会想,既然循环次数固定,为什么不直接手动循环展开呢,难道就为了使用模板吗?
当然不是,有时候循环次数确实是编译期固定值,但对用户并不是固定的,比如要实现数学上向量计算的类,
因为可能是 2、3、4 维,所以写成模板,把维度作为 int 型模板参数,这时因为不知道具体是几维的也就不得不用循环,
不过因为维度信息在模板实例化时是编译期常量且较小,所以编译器很可能在代码优化时进行循环展开,但我们想让这一切发生的更可控一些。

上面用三个函数模板 IntSwap<>()、 IntBubbleSortLoop<>()、 IntBubbleSort<>() 来实现一个排序功能,不但显得分散(和封装原理不符),
还暴露了实现细节,我们可以仿照上一节的代码,将 IntBubbleSortLoop<>()、 IntBubbleSort<>() 嵌入其他模板内部,因为函数不允许嵌套,我们只能用类模板:


  1. // 整合成一个类模板实现,看着好,但引入了 代码膨胀
  2. template<int n>
  3. class IntBubbleSortC {
  4.     template<int i, int j>
  5.     static inline void IntSwap(int* data) { // 比较和交换两个相邻元素
  6.         if(data[i]>data[j]) std::swap(data[i], data[j]);
  7.     }
  8.     template<int i, int j>
  9.     static inline void IntBubbleSortLoop(int* data) { // 一次冒泡
  10.         IntSwap<j, j+1>(data);
  11.         IntBubbleSortLoop<j<i-1?i:0, j<i-1?(j+1):0>(data);
  12.     }
  13.     template<>
  14.     static inline void IntBubbleSortLoop<0, 0>(int*) { }
  15. public:
  16.     static inline void sort(int* data) {
  17.         IntBubbleSortLoop<n-1, 0>(data);
  18.         IntBubbleSortC<n-1>::sort(data);
  19.     }
  20. };
  21. template<>
  22. class IntBubbleSortC<0> {
  23. public:
  24.     static inline void sort(int* data) { }
  25. };

  26. int main() {
  27.     int data[4] = {3,4,2,1};
  28.     IntBubbleSortC<4>::sort(data); // 如此调用
  29.     std::cin.get(); return 0;
  30. }
复制代码


上面代码看似很好,不仅整合了代码,借助类成员的访问控制,还隐藏了实现细节。
不过它存在着很大问题,如果实例化 IntBubbleSortC<4>、 IntBubbleSortC<3>、 IntBubbleSortC<2>,
将实例化成员函数 IntBubbleSortC<4>::IntSwap<0, 1>()、 IntBubbleSortC<4>::IntSwap<1, 2>()、 IntBubbleSortC<4>::IntSwap<2, 3>()、 IntBubbleSortC<3>::IntSwap<0, 1>()、 IntBubbleSortC<3>::IntSwap<1, 2>()、 IntBubbleSortC<2>::IntSwap<0, 1>(),
而在原来的看着分散的代码中 IntSwap<0, 1>() 只有一个。

这将导致代码膨胀(code bloat),即生成的可执行文件体积变大(代码膨胀另一含义是源代码增大,见文献[1]第11章)。
不过这里使用了内联(inline),如果编译器确实内联展开代码则不会导致代码膨胀(除了循环展开本身会带来的代码膨胀),但因为重复编译原本可以复用的模板实例,会增加编译时间。
在上一节的例子中,因为只涉及编译期常量计算,并不涉及函数(函数模板,或类模板的成员函数,函数被编译成具体的机器二进制代码),并不会出现代码膨胀。

为了清晰证明上面的论述,我们去掉所有 inline 并将函数实现放到类外面(类里面实现的成员函数都是内联的,因为函数实现可能被包含多次,见文献[2] 10.2.9,
不过现在的编译器优化能力很强,很多时候加不加 inline 并不影响编译器自己对内联的选择...),
分别编译分散版本和类模板封装版本的冒泡排序代码编译生成的目标文件(VS2013 下是 .obj 文件)的大小,
代码均在 VS2013 Debug 模式下编译(防止编译器优化),比较 main.obj (源文件是 main.cpp)大小。

类模板封装版本代码如下,注意将成员函数在外面定义的写法:


  1. #include <iostream>
  2. #include <utility>  // std::swap

  3. // 整合成一个类模板实现,看着好,但引入了 代码膨胀
  4. template<int n>
  5. class IntBubbleSortC {
  6.     template<int i, int j> static void IntSwap(int* data);
  7.     template<int i, int j> static void IntBubbleSortLoop(int* data);
  8.     template<> static void IntBubbleSortLoop<0, 0>(int*) { }
  9. public:
  10.     static void sort(int* data);
  11. };
  12. template<>
  13. class IntBubbleSortC<0> {
  14. public:
  15.     static void sort(int* data) { }
  16. };

  17. template<int n> template<int i, int j>
  18. void IntBubbleSortC<n>::IntSwap(int* data) {
  19.     if(data[i]>data[j]) std::swap(data[i], data[j]);
  20. }
  21. template<int n> template<int i, int j>
  22. void IntBubbleSortC<n>::IntBubbleSortLoop(int* data) {
  23.     IntSwap<j, j+1>(data);
  24.     IntBubbleSortLoop<j<i-1?i:0, j<i-1?(j+1):0>(data);
  25. }
  26. template<int n>
  27. void IntBubbleSortC<n>::sort(int* data) {
  28.     IntBubbleSortLoop<n-1, 0>(data);
  29.     IntBubbleSortC<n-1>::sort(data);
  30. }

  31. int main() {
  32.     int data[40] = {3,4,2,1};
  33.     IntBubbleSortC<2>::sort(data);  IntBubbleSortC<3>::sort(data);
  34.     IntBubbleSortC<4>::sort(data);  IntBubbleSortC<5>::sort(data);
  35.     IntBubbleSortC<6>::sort(data);  IntBubbleSortC<7>::sort(data);
  36.     IntBubbleSortC<8>::sort(data);  IntBubbleSortC<9>::sort(data);
  37.     IntBubbleSortC<10>::sort(data); IntBubbleSortC<11>::sort(data);
  38. #if 0
  39.     IntBubbleSortC<12>::sort(data); IntBubbleSortC<13>::sort(data);
  40.     IntBubbleSortC<14>::sort(data); IntBubbleSortC<15>::sort(data);
  41.     IntBubbleSortC<16>::sort(data); IntBubbleSortC<17>::sort(data);
  42.     IntBubbleSortC<18>::sort(data); IntBubbleSortC<19>::sort(data);
  43.     IntBubbleSortC<20>::sort(data); IntBubbleSortC<21>::sort(data);

  44.     IntBubbleSortC<22>::sort(data); IntBubbleSortC<23>::sort(data);
  45.     IntBubbleSortC<24>::sort(data); IntBubbleSortC<25>::sort(data);
  46.     IntBubbleSortC<26>::sort(data); IntBubbleSortC<27>::sort(data);
  47.     IntBubbleSortC<28>::sort(data); IntBubbleSortC<29>::sort(data);
  48.     IntBubbleSortC<30>::sort(data); IntBubbleSortC<31>::sort(data);
  49. #endif
  50.     std::cin.get(); return 0;
  51. }
复制代码


分散定义函数模板版本代码如下,为了更具可比性,也将函数放在类里面作为成员函数:


  1. #include <iostream>
  2. #include <utility>  // std::swap

  3. // static code, 模板元编程版本
  4. template<int i, int j>
  5. class IntSwap {
  6. public: static void swap(int* data);
  7. };

  8. template<int i, int j>
  9. class IntBubbleSortLoop {
  10. public: static void loop(int* data);
  11. };
  12. template<>
  13. class IntBubbleSortLoop<0, 0> {
  14. public: static void loop(int* data) { }
  15. };

  16. template<int n>
  17. class IntBubbleSort {
  18. public: static void sort(int* data);
  19. };
  20. template<>
  21. class IntBubbleSort<0> {
  22. public: static void sort(int* data) { }
  23. };

  24. template<int i, int j>
  25. void IntSwap<i, j>::swap(int* data) {
  26.     if(data[i]>data[j]) std::swap(data[i], data[j]);
  27. }
  28. template<int i, int j>
  29. void IntBubbleSortLoop<i, j>::loop(int* data) {
  30.     IntSwap<j, j+1>::swap(data);
  31.     IntBubbleSortLoop<j<i-1?i:0, j<i-1?(j+1):0>::loop(data);
  32. }
  33. template<int n>
  34. void IntBubbleSort<n>::sort(int* data) {
  35.     IntBubbleSortLoop<n-1, 0>::loop(data);
  36.     IntBubbleSort<n-1>::sort(data);
  37. }

  38. int main() {
  39.     int data[40] = {3,4,2,1};
  40.     IntBubbleSort<2>::sort(data);  IntBubbleSort<3>::sort(data);
  41.     IntBubbleSort<4>::sort(data);  IntBubbleSort<5>::sort(data);
  42.     IntBubbleSort<6>::sort(data);  IntBubbleSort<7>::sort(data);
  43.     IntBubbleSort<8>::sort(data);  IntBubbleSort<9>::sort(data);
  44.     IntBubbleSort<10>::sort(data); IntBubbleSort<11>::sort(data);
  45. #if 0
  46.     IntBubbleSort<12>::sort(data); IntBubbleSort<13>::sort(data);
  47.     IntBubbleSort<14>::sort(data); IntBubbleSort<15>::sort(data);
  48.     IntBubbleSort<16>::sort(data); IntBubbleSort<17>::sort(data);
  49.     IntBubbleSort<18>::sort(data); IntBubbleSort<19>::sort(data);
  50.     IntBubbleSort<20>::sort(data); IntBubbleSort<21>::sort(data);

  51.     IntBubbleSort<22>::sort(data); IntBubbleSort<23>::sort(data);
  52.     IntBubbleSort<24>::sort(data); IntBubbleSort<25>::sort(data);
  53.     IntBubbleSort<26>::sort(data); IntBubbleSort<27>::sort(data);
  54.     IntBubbleSort<28>::sort(data); IntBubbleSort<29>::sort(data);
  55.     IntBubbleSort<30>::sort(data); IntBubbleSort<31>::sort(data);
  56. #endif
  57.     std::cin.get(); return 0;
  58. }
复制代码


程序中条件编译都未打开时(#if 0),main.obj 大小分别为 264 KB 和 211 KB,条件编译打开时(#if 1),main.obj 大小分别为 1073 KB 和 620 KB。
可以看到,类模板封装版的对象文件不但绝对大小更大,而且增长更快,这和之前分析是一致的。



6. 表达式模板,向量运算

文献[12]展示了一个表达式模板(Expression Templates)的例子:


  1. #include <iostream> // std::cout
  2. #include <cmath>    // std::sqrt()

  3. // 表达式类型
  4. class DExprLiteral {                    // 文字量
  5.     double a_;
  6. public:
  7.     DExprLiteral(double a) : a_(a) { }
  8.     double operator()(double x) const { return a_; }
  9. };
  10. class DExprIdentity {                   // 自变量
  11. public:
  12.     double operator()(double x) const { return x; }
  13. };
  14. template<class A, class B, class Op>    // 双目操作
  15. class DBinExprOp {
  16.     A a_; B b_;
  17. public:
  18.     DBinExprOp(const A& a, const B& b) : a_(a), b_(b) { }
  19.     double operator()(double x) const { return Op::apply(a_(x), b_(x)); }
  20. };
  21. template<class A, class Op>             // 单目操作
  22. class DUnaryExprOp {
  23.     A a_;
  24. public:
  25.     DUnaryExprOp(const A& a) : a_(a) { }
  26.     double operator()(double x) const { return Op::apply(a_(x)); }
  27. };
  28. // 表达式
  29. template<class A>
  30. class DExpr {
  31.     A a_;
  32. public:
  33.     DExpr() { }
  34.     DExpr(const A& a) : a_(a) { }
  35.     double operator()(double x) const { return a_(x); }
  36. };

  37. // 运算符,模板参数 A、B 为参与运算的表达式类型
  38. // operator /, division
  39. class DApDiv { public: static double apply(double a, double b) { return a / b; } };
  40. template<class A, class B> DExpr<DBinExprOp<DExpr<A>, DExpr<B>, DApDiv> >
  41. operator/(const DExpr<A>& a, const DExpr<B>& b) {
  42.     typedef DBinExprOp<DExpr<A>, DExpr<B>, DApDiv> ExprT;
  43.     return DExpr<ExprT>(ExprT(a, b));
  44. }
  45. // operator +, addition
  46. class DApAdd { public: static double apply(double a, double b) { return a + b; } };
  47. template<class A, class B> DExpr<DBinExprOp<DExpr<A>, DExpr<B>, DApAdd> >
  48. operator+(const DExpr<A>& a, const DExpr<B>& b) {
  49.     typedef DBinExprOp<DExpr<A>, DExpr<B>, DApAdd> ExprT;
  50.     return DExpr<ExprT>(ExprT(a, b));
  51. }
  52. // sqrt(), square rooting
  53. class DApSqrt { public: static double apply(double a) { return std::sqrt(a); } };
  54. template<class A> DExpr<DUnaryExprOp<DExpr<A>, DApSqrt> >
  55. sqrt(const DExpr<A>& a) {
  56.     typedef DUnaryExprOp<DExpr<A>, DApSqrt> ExprT;
  57.     return DExpr<ExprT>(ExprT(a));
  58. }
  59. // operator-, negative sign
  60. class DApNeg { public: static double apply(double a) { return -a; } };
  61. template<class A> DExpr<DUnaryExprOp<DExpr<A>, DApNeg> >
  62. operator-(const DExpr<A>& a) {
  63.     typedef DUnaryExprOp<DExpr<A>, DApNeg> ExprT;
  64.     return DExpr<ExprT>(ExprT(a));
  65. }

  66. // evaluate()
  67. template<class Expr>
  68. void evaluate(const DExpr<Expr>& expr, double start, double end, double step) {
  69.     for(double i=start; i<end; i+=step) std::cout << expr(i) << ' ';
  70. }

  71. int main() {
  72.     DExpr<DExprIdentity> x;
  73.     evaluate( -x / sqrt( DExpr<DExprLiteral>(1.0) + x ) , 0.0, 10.0, 1.0);
  74.     std::cin.get(); return 0;
  75. }
复制代码


  1. -0 -0.707107 -1.1547 -1.5 -1.78885 -2.04124 -2.26779 -2.47487 -2.66667 -2.84605
复制代码


代码有点长(我已经尽量压缩行数),请先看最下面的 main() 函数,表达式模板允许我们以 “-x / sqrt( 1.0 + x )” 这种类似数学表达式的方式传参数,
在 evaluate() 内部,将 0-10 的数依次赋给自变量 x 对表达式进行求值,这是通过在 template<> DExpr 类模板内部重载 operator() 实现的。我们来看看这一切是如何发生的。

在 main() 中调用 evaluate() 时,编译器根据全局重载的加号、sqrt、除号、负号推断“-x / sqrt( 1.0 + x )” 的类型是 Dexpr<DBinExprOp<Dexpr<DUnaryExprOp<Dexpr<DExprIdentity>, DApNeg>>, Dexpr<DUnaryExprOp<Dexpr<DBinExprOp<Dexpr<DExprLiteral>, Dexpr<DExprIdentity>, DApAdd>>, DApSqrt>>, DApDiv>>(即将每个表达式编码到一种类型,设这个类型为 ultimateExprType),
并用此类型实例化函数模板 evaluate(),类型的推导见下图。

在 evaluate() 中,对表达式进行求值 expr(i),调用 ultimateExprType 的 operator(),这引起一系列的 operator() 和 Op::apply() 的调用,
最终遇到基础类型 “表达式类型” DExprLiteral 和 DExprIdentity,这个过程见下图。总结就是,请看下图,从下到上类型推断,从上到下 operator() 表达式求值。

表达式求职.png

上面代码函数实现写在类的内部,即内联,如果编译器对内联支持的好的话,上面代码几乎等价于如下代码:


  1. #include <iostream> // std::cout
  2. #include <cmath>    // std::sqrt()

  3. void evaluate(double start, double end, double step) {
  4.     double _temp = 1.0;
  5.     for(double i=start; i<end; i+=step)
  6.         std::cout << -i / std::sqrt(_temp + i) << ' ';
  7. }

  8. int main() {
  9.     evaluate(0.0, 10.0, 1.0);
  10.     std::cin.get(); return 0;
  11. }
复制代码

  1. -0 -0.707107 -1.1547 -1.5 -1.78885 -2.04124 -2.26779 -2.47487 -2.66667 -2.84605
复制代码


和表达式模板类似的技术还可以用到向量计算中,以避免产生临时向量变量,见文献[4] Expression templates 和文献[12]的后面。传统向量计算如下:


  1. class DoubleVec; // DoubleVec 重载了 + - * / 等向量元素之间的计算
  2. DoubleVec y(1000), a(1000), b(1000), c(1000), d(1000); // 向量长度 1000
  3. // 向量计算
  4. y = (a + b) / (c - d);
  5. // 等价于
  6. DoubleVec __t1 = a + b;
  7. DoubleVec __t2 = c - d;
  8. DoubleVec __t3 = __t1 / __t2;
  9. y = __t3;
复制代码


模板代码实现向量计算如下:


  1. template<class A> DVExpr;
  2. class DVec{
  3.     // ...
  4.     template<class A>
  5.     DVec& operator=(const DVExpr<A>&); // 由 = 引起向量逐个元素的表达式值计算并赋值
  6. };
  7. DVec y(1000), a(1000), b(1000), c(1000), d(1000); // 向量长度 1000
  8. // 向量计算
  9. y = (a + b) / (c - d);
  10. // 等价于
  11. for(int i=0; i<1000; ++i) {
  12.     y[i] = (a[i] + b[i]) / (c[i] + d[i]);
  13. }
复制代码


不过值得一提的是,传统代码可以用 C++11 的右值引用提升性能,C++11 新特性我们以后再详细讨论。

我们这里看下文献[4] Expression templates 实现的版本,它用到了编译期多态,编译期多态示意代码如下(关于这种代码形式有个名字叫 curiously recurring template pattern, CRTP,见文献[4]):


  1. // 模板基类,定义接口,具体实现由模板参数,即子类实现
  2. template <typename D>
  3. class base {
  4. public:
  5.     void f1() { static_cast<E&>(*this).f1(); } // 直接调用子类实现
  6.     int f2() const { static_cast<const E&>(*this).f1(); }
  7. };
  8. // 子类
  9. class dirived1 : public base<dirived1> {
  10. public:
  11.     void f1() { /* ... */ }
  12.     int f2() const { /* ... */ }
  13. };
  14. template<typename T>
  15. class dirived2 : public base<dirived2<T>> {
  16. public:
  17.     void f1() { /* ... */ }
  18.     int f2() const { /* ... */ }
  19. };
复制代码


简化后(向量长度固定为1000,元素类型为 double)的向量计算代码如下:


  1. #include <iostream> // std::cout

  2. // A CRTP base class for Vecs with a size and indexing:
  3. template <typename E>
  4. class VecExpr {
  5. public:
  6.     double operator[](int i) const { return static_cast<E const&>(*this)[i]; }
  7.     operator E const&() const { return static_cast<const E&>(*this); } // 向下类型转换
  8. };
  9. // The actual Vec class:
  10. class Vec : public VecExpr<Vec> {
  11.     double _data[1000];
  12. public:
  13.     double&  operator[](int i) { return _data[i]; }
  14.     double operator[](int i) const { return _data[i]; }
  15.     template <typename E>
  16.     Vec const& operator=(VecExpr<E> const& vec) {
  17.         E const& v = vec;
  18.         for (int i = 0; i<1000; ++i) _data[i] = v[i];
  19.         return *this;
  20.     }
  21.     // Constructors
  22.     Vec() { }
  23.     Vec(double v) { for(int i=0; i<1000; ++i) _data[i] = v; }
  24. };

  25. template <typename E1, typename E2>
  26. class VecDifference : public VecExpr<VecDifference<E1, E2> > {
  27.     E1 const& _u; E2 const& _v;
  28. public:
  29.     VecDifference(VecExpr<E1> const& u, VecExpr<E2> const& v) : _u(u), _v(v) { }
  30.     double operator[](int i) const { return _u[i] - _v[i]; }
  31. };
  32. template <typename E>
  33. class VecScaled : public VecExpr<VecScaled<E> > {
  34.     double _alpha; E const& _v;
  35. public:
  36.     VecScaled(double alpha, VecExpr<E> const& v) : _alpha(alpha), _v(v) { }
  37.     double operator[](int i) const { return _alpha * _v[i]; }
  38. };

  39. // Now we can overload operators:
  40. template <typename E1, typename E2> VecDifference<E1, E2> const
  41. operator-(VecExpr<E1> const& u, VecExpr<E2> const& v) {
  42.     return VecDifference<E1, E2>(u, v);
  43. }
  44. template <typename E> VecScaled<E> const
  45. operator*(double alpha, VecExpr<E> const& v) {
  46.     return VecScaled<E>(alpha, v);
  47. }

  48. int main() {
  49.     Vec u(3), v(1); double alpha=9; Vec y;
  50.     y = alpha*(u - v);
  51.     std::cout << y[999] << '\n';
  52.     std::cin.get(); return 0;
  53. }
复制代码

  1. 18
复制代码


“alpha*(u - v)” 的类型推断过程如下图所示,其中有子类到基类的隐式类型转换:

alpha.png


这里可以看到基类的作用:提供统一的接口,让 operator- 和 operator* 可以写成统一的模板形式。



7. 特性,策略,标签

利用迭代器,我们可以实现很多通用算法,迭代器在容器与算法之间搭建了一座桥梁。求和函数模板如下:



  1. #include <iostream> // std::cout
  2. #include <vector>

  3. template<typename iter>
  4. typename iter::value_type mysum(iter begin, iter end) {
  5.     typename iter::value_type sum(0);
  6.     for(iter i=begin; i!=end; ++i) sum += *i;
  7.     return sum;
  8. }

  9. int main() {
  10.     std::vector<int> v;
  11.     for(int i = 0; i<100; ++i) v.push_back(i);
  12.     std::cout << mysum(v.begin(), v.end()) << '\n';
  13.     std::cin.get(); return 0;
  14. }
复制代码

  1. 4950
复制代码


我们想让 mysum() 对指针参数也能工作,毕竟迭代器就是模拟指针,但指针没有嵌套类型 value_type,可以定义 mysum() 对指针类型的特例,
但更好的办法是在函数参数和 value_type 之间多加一层 -- 特性(traits)(参考了文献[1]第72页,特性详见文献[1] 12.1):


  1. // 特性,traits
  2. template<typename iter>
  3. class mytraits{
  4. public: typedef typename iter::value_type value_type;
  5. };
  6. template<typename T>
  7. class mytraits<T*>{
  8. public: typedef T value_type;
  9. };

  10. template<typename iter>
  11. typename mytraits<iter>::value_type mysum(iter begin, iter end) {
  12.     typename mytraits<iter>::value_type sum(0);
  13.     for(iter i=begin; i!=end; ++i) sum += *i;
  14.     return sum;
  15. }

  16. int main() {
  17.     int v[4] = {1,2,3,4};
  18.     std::cout << mysum(v, v+4) << '\n';
  19.     std::cin.get(); return 0;
  20. }
复制代码

  1. 10
复制代码


其实,C++ 标准定义了类似的 traits:std::iterator_trait(另一个经典例子是 std::numeric_limits) 。
特性对类型的信息(如 value_type、 reference)进行包装,使得上层代码可以以统一的接口访问这些信息。
C++ 模板元编程会涉及大量的类型计算,很多时候要提取类型的信息(typedef、 常量值等),如果这些类型的信息的访问方式不一致(如上面的迭代器和指针),我们将不得不定义特例,
这会导致大量重复代码的出现(另一种代码膨胀),而通过加一层特性可以很好的解决这一问题。
另外,特性不仅可以对类型的信息进行包装,还可以提供更多信息,当然,因为加了一层,也带来复杂性。
特性是一种提供元信息的手段。

策略(policy)一般是一个类模板,典型的策略是 STL 容器(如 std::vector<>,完整声明是template<class T, class Alloc=allocator<T>> class vector;)的分配器(这个参数有默认参数,即默认存储策略),
策略类将模板的经常变化的那一部分子功能块集中起来作为模板参数,这样模板便可以更为通用,这和特性的思想是类似的(详见文献[1] 12.3)。

标签(tag)一般是一个空类,其作用是作为一个独一无二的类型名字用于标记一些东西,
典型的例子是 STL 迭代器的五种类型的名字(input_iterator_tag, output_iterator_tag, forward_iterator_tag, bidirectional_iterator_tag, random_access_iterator_tag),std::vector<int>::iterator::iterator_category 就是 random_access_iterator_tag,
可以用第1节判断类型是否等价的模板检测这一点:


  1. #include <iostream>
  2. #include <vector>

  3. template<typename T1, typename T2> // 通例,返回 false
  4. class theSameType       { public: enum { ret = false }; };
  5. template<typename T>               // 特例,两类型相同时返回 true
  6. class theSameType<T, T> { public: enum { ret = true }; };

  7. int main(){
  8.     std::cout << theSameType< std::vector<int>::iterator::iterator_category,
  9.                               std::random_access_iterator_tag >::ret << '\n';
  10.     std::cin.get(); return 0;
  11. }
复制代码

  1. 1
复制代码


有了这样的判断,还可以根据判断结果做更复杂的元编程逻辑(如一个算法以迭代器为参数,根据迭代器标签进行特例化以对某种迭代器特殊处理)。
标签还可以用来分辨函数重载,第5节中就用到了这样的标签(recursion)(标签详见文献[1] 12.1)。



8. 更多类型计算

在第1节我们讲类型等价的时候,已经见到了一个可以判断两个类型是否等价的模板,这一节我们给出更多例子,
下面是判断一个类型是否可以隐式转换到另一个类型的模板(参考了文献[6] Static interface checking):


  1. #include <iostream> // std::cout

  2. // whether T could be converted to U
  3. template<class T, class U>
  4. class ConversionTo {
  5.     typedef char Type1[1]; // 两种 sizeof 不同的类型
  6.     typedef char Type2[2];
  7.     static Type1& Test( U ); // 较下面的函数,因为参数取值范围小,优先匹配
  8.     static Type2& Test(...); // 变长参数函数,可以匹配任何数量任何类型参数
  9.     static T MakeT(); // 返回类型 T,用这个函数而不用 T() 因为 T 可能没有默认构造函数
  10. public:
  11.     enum { ret = sizeof(Test(MakeT()))==sizeof(Type1) }; // 可以转换时调用返回 Type1 的 Test()
  12. };

  13. int main() {
  14.     std::cout << ConversionTo<int, double>::ret << '\n';
  15.     std::cout << ConversionTo<float, int*>::ret << '\n';
  16.     std::cout << ConversionTo<const int&, int&>::ret << '\n';
  17.     std::cin.get(); return 0;
  18. }
复制代码

  1. 1
  2. 0
  3. 0
复制代码

下面这个例子检查某个类型是否含有某个嵌套类型定义(参考了文献[4] Substitution failure is not an erro (SFINAE)),这个例子是个内省(反射的一种):


  1. #include <iostream>
  2. #include <vector>

  3. // thanks to Substitution failure is not an erro (SFINAE)
  4. template<typename T>
  5. struct has_typedef_value_type {
  6.     typedef char Type1[1];
  7.     typedef char Type2[2];
  8.     template<typename C> static Type1& test(typename C::value_type*);
  9.     template<typename> static Type2& test(...);
  10. public:
  11.     static const bool ret = sizeof(test<T>(0)) == sizeof(Type1); // 0 == NULL
  12. };

  13. struct foo { typedef float lalala; };

  14. int main() {
  15.     std::cout << has_typedef_value_type<std::vector<int>>::ret << '\n';
  16.     std::cout << has_typedef_value_type<foo>::ret << '\n';
  17.     std::cin.get(); return 0;
  18. }
复制代码

  1. 1
  2. 0
复制代码


这个例子是有缺陷的,因为不存在引用的指针,所以不用用来检测引用类型定义。
可以看到,因为只涉及类型推断,都是编译期的计算,不涉及任何可执行代码,所以类的成员函数根本不需要具体实现。



9. 元容器

文献[1]第 13 章讲了元容器,所谓元容器,就是类似于 std::vector<> 那样的容器,不过它存储的是元数据 -- 类型,有了元容器,我们就可以判断某个类型是否属于某个元容器之类的操作。

在讲元容器之前,我们先来看看伪变长参数模板(文献[1] 12.4),一个可以存储小于某个数(例子中为 4 个)的任意个数,任意类型数据的元组(tuple)的例子如下(参考了文献[1] 第 225~227 页):



  1. #include <iostream>

  2. class null_type {}; // 标签类,标记参数列表末尾
  3. template<typename T0, typename T1, typename T2, typename T3>
  4. class type_shift_node {
  5. public:
  6.     typedef T0 data_type;
  7.     typedef type_shift_node<T1, T2, T3, null_type> next_type; // 参数移位了
  8.     static const int num = next_type::num + 1; // 非 null_type 模板参数个数
  9.     data_type data; // 本节点数据
  10.     next_type next; // 后续所有节点数据
  11.     type_shift_node() :data(), next() { } // 构造函数
  12.     type_shift_node(T0 const& d0, T1 const& d1, T2 const& d2, T3 const& d3)
  13.         :data(d0), next(d1, d2, d3, null_type()) { } // next 参数也移位了
  14. };
  15. template<typename T0> // 特例,递归终止
  16. class type_shift_node<T0, null_type, null_type, null_type> {
  17. public:
  18.     typedef T0 data_type;
  19.     static const int num = 1;
  20.     data_type data; // 本节点数据
  21.     type_shift_node() :data(), next() { } // 构造函数
  22.     type_shift_node(T0 const& d0, null_type, null_type, null_type) : data(d0) { }
  23. };
  24. // 元组类模板,默认参数 + 嵌套递归
  25. template<typename T0, typename T1=null_type, typename T2=null_type,
  26.          typename T3=null_type>
  27. class my_tuple {
  28. public:
  29.     typedef type_shift_node<T0, T1, T2, T3> tuple_type;
  30.     static const int num = tuple_type::num;
  31.     tuple_type t;
  32.     my_tuple(T0 const& d0=T0(),T1 const& d1=T1(),T2 const& d2=T2(),T3 const& d3=T3())
  33.         : t(d0, d1, d2, d3) { } // 构造函数,默认参数
  34. };

  35. // 为方便访问元组数据,定义 get<unsigned>(tuple) 函数模板
  36. template<unsigned i, typename T0, typename T1, typename T2, typename T3>
  37. class type_shift_node_traits {
  38. public:
  39.     typedef typename
  40.         type_shift_node_traits<i-1,T0,T1,T2,T3>::node_type::next_type node_type;
  41.     typedef typename node_type::data_type data_type;
  42.     static node_type& get_node(type_shift_node<T0,T1,T2,T3>& node)
  43.     { return type_shift_node_traits<i-1,T0,T1,T2,T3>::get_node(node).next; }
  44. };
  45. template<typename T0, typename T1, typename T2, typename T3>
  46. class type_shift_node_traits<0, T0, T1, T2, T3> {
  47. public:
  48.     typedef typename type_shift_node<T0,T1,T2,T3> node_type;
  49.     typedef typename node_type::data_type data_type;
  50.     static node_type& get_node(type_shift_node<T0,T1,T2,T3>& node)
  51.     { return node; }
  52. };
  53. template<unsigned i, typename T0, typename T1, typename T2, typename T3>
  54. typename type_shift_node_traits<i,T0,T1,T2,T3>::data_type
  55. get(my_tuple<T0,T1,T2,T3>& tup) {
  56.     return type_shift_node_traits<i,T0,T1,T2,T3>::get_node(tup.t).data;
  57. }

  58. int main(){
  59.     typedef my_tuple<int, char, float> tuple3;
  60.     tuple3 t3(10, 'm', 1.2f);
  61.     std::cout << t3.t.data << ' '
  62.               << t3.t.next.data << ' '
  63.               << t3.t.next.next.data << '\n';
  64.     std::cout << tuple3::num << '\n';
  65.     std::cout << get<2>(t3) << '\n'; // 从 0 开始,不要出现 3,否则将出现不可理解的编译错误
  66.     std::cin.get(); return 0;
  67. }
复制代码

  1. 10 m 1.2
  2. 3
  3. 1.2
复制代码


C++11 引入了变长模板参数,其背后的原理也是模板递归(文献[1]第 230 页)。

利用和上面例子类似的模板参数移位递归的原理,我们可以构造一个存储“类型”的元组,即元容器,其代码如下(和文献[1]第 237 页的例子不同):


  1. #include <iostream>

  2. // 元容器
  3. template<typename T0=void, typename T1=void, typename T2=void, typename T3=void>
  4. class meta_container {
  5. public:
  6.     typedef T0 type;
  7.     typedef meta_container<T1, T2, T3, void> next_node; // 参数移位了
  8.     static const int size = next_node::size + 1; // 非 null_type 模板参数个数
  9. };
  10. template<> // 特例,递归终止
  11. class meta_container<void, void, void, void> {
  12. public:
  13.     typedef void type;
  14.     static const int size = 0;
  15. };

  16. // 访问元容器中的数据
  17. template<typename C, unsigned i>
  18. class get {
  19. public:
  20.     static_assert(i<C::size, "get<C,i>: index exceed num"); // C++11 引入静态断言
  21.     typedef typename get<C,i-1>::c_type::next_node c_type;
  22.     typedef typename c_type::type ret_type;
  23. };
  24. template<typename C>
  25. class get<C, 0> {
  26. public:
  27.     static_assert(0<C::size, "get<C,i>: index exceed num"); // C++11 引入静态断言
  28.     typedef C c_type;
  29.     typedef typename c_type::type ret_type;
  30. };

  31. // 在元容器中查找某个类型,找到返回索引,找不到返回 -1
  32. template<typename T1, typename T2> class same_type { public: enum { ret = false }; };
  33. template<typename T> class same_type<T, T> { public: enum { ret = true }; };

  34. template<bool c, typename Then, typename Else> class IF_ { };
  35. template<typename Then, typename Else>
  36. class IF_<true, Then, Else> { public: typedef Then reType; };
  37. template<typename Then, typename Else>
  38. class IF_<false, Then, Else> { public: typedef Else reType; };

  39. template<typename C, typename T>
  40. class find {
  41.     template<int i> class number { public: static const int ret = i; };
  42.     template<typename C, typename T, int i>
  43.     class find_i {
  44.     public:
  45.         static const int ret = IF_< same_type<get<C,i>::ret_type, T>::ret,
  46.             number<i>, find_i<C,T,i-1> >::reType::ret;
  47.     };
  48.     template<typename C, typename T>
  49.     class find_i<C, T, -1> {
  50.     public:
  51.         static const int ret = -1;
  52.     };
  53. public:
  54.     static const int ret = find_i<C, T, C::size-1>::ret;
  55. };

  56. int main(){
  57.     typedef meta_container<int, int&, const int> mc;
  58.     int a = 9999;
  59.     get<mc, 1>::ret_type aref = a;
  60.     std::cout << mc::size << '\n';
  61.     std::cout << aref << '\n';
  62.     std::cout << find<mc, const int>::ret << '\n';
  63.     std::cout << find<mc, float>::ret << '\n';
  64.     std::cin.get(); return 0;
  65. }
复制代码

  1. 3
  2. 9999
  3. 2
  4. -1
复制代码


上面例子已经实现了存储类型的元容器,和元容器上的查找算法,但还有一个小问题,就是它不能处理模板,编译器对模板的操纵能力远不如对类型的操纵能力强(提示:类模板实例是类型),我们可以一种间接方式实现存储“模板元素”,即用模板的一个代表实例(如全用 int 为参数的实例)来代表这个模板,这样对任意模板实例,只需判断其模板的代表实例是否在容器中即可,这需要进行类型过滤:对任意模板的实例将其替换为指定模板参数的代表实例,类型过滤实例代码如下(参考了文献[1]第 241 页):


  1. // 类型过滤,meta_filter 使用时只用一个参数,设置四个模板参数是因为,模板通例的参数列表
  2. // 必须能够包含特例参数列表,后面三个参数设置默认值为 void 或标签模板
  3. template<typename T> class dummy_template_1 {};
  4. template<typename T0, typename T1> class dummy_template_2 {};
  5. template<typename T0, typename T1 = void,
  6.     template<typename> class tmp_1 = dummy_template_1,
  7.     template<typename, typename> class tmp_2 = dummy_template_2>
  8. class meta_filter { // 通例,不改变类型
  9. public:
  10.     typedef T0 ret_type;
  11. };
  12.                     // 匹配任何带有一个类型参数模板的实例,将模板实例替换为代表实例
  13. template<template<typename> class tmp_1, typename T>
  14. class meta_filter<tmp_1<T>, void, dummy_template_1, dummy_template_2> {
  15. public:
  16.     typedef tmp_1<int> ret_type;
  17. };
  18.                     // 匹配任何带有两个类型参数模板的实例,将模板实例替换为代表实例
  19. template<template<typename, typename> class tmp_2, typename T0, typename T1>
  20. class meta_filter<tmp_2<T0, T1>, void, dummy_template_1, dummy_template_2> {
  21. public:
  22.     typedef tmp_2<int, int> ret_type;
  23. };
复制代码


现在,只需将上面元容器和元容器查找函数修改为:对模板实例将其换为代表实例,
即修改 meta_container<> 通例中“typedef T0 type;”语句为“typedef typename meta_filter<T0>::ret_type type;”,修改 find<> 的最后一行中“T”为“typename meta_filter<T>::ret_type”。
修改后,下面代码的执行结果是:


  1. template<typename, typename> class my_tmp_2;

  2. // 自动将 my_tmp_2<float, int> 过滤为 my_tmp_2<int, int>
  3. typedef meta_container<int, float, my_tmp_2<float, int>> mc2;
  4. // 自动将 my_tmp_2<char, double> 过滤为 my_tmp_2<int, int>
  5. std::cout << find<mc2, my_tmp_2<char, double>>::ret << '\n'; // 输出 2
复制代码

  1. 2
复制代码



10. 总结

博文比较长,总结一下所涉及的东西:

  • C++ 模板包括函数模板和类模板,模板参数形式有:类型、模板型、非类型(整型、指针);
  • 模板的特例化分完全特例化和部分特例化,实例将匹配参数集合最小的特例;
  • 用实例参数替换模板形式参数称为实例化,实例化的结果是产生具体类型(类模板)或函数(函数模板),同一模板实参完全等价将产生等价的实例类型或函数;
  • 模板一般在头文件中定义,可能被包含多次,编译和链接时会消除等价模板实例;
  • template、typename、this 关键字用来消除歧义,避免编译错误或产生不符预期的结果;
  • C++11 对模板引入了新特性:“>>”、函数模板也可以有默认参数、变长模板参数、外部模板实例(extern),并弃用 export template;
  • C++ 模板是图灵完备的,模板编程是函数编程风格,特点是:没有可变的存储、递归,以“<>”为输入,typedef 或静态常量为输出;
  • 编译期数值计算虽然实际意义不大,但可以很好证明 C++ 模板的能力,可以用模板实现类似普通程序中的 if 和 while 语句;
  • 一个实际应用是循环展开,虽然编译器可以自动循环展开,但我们可以让这一切更可控;
  • C++ 模板编程的两个问题是:难调试,会产生冗长且难以阅读的编译错误信息、代码膨胀(源代码膨胀、二进制对象文件膨胀),改进的方法是:增加一些检查代码,让编译器及时报错,使用特性、策略等让模板更通用,可能的话合并一些模板实例(如将代码提出去做成单独模板);
  • 表达式模板和向量计算是另一个可加速程序的例子,它们将计算表达式编码到类型,这是通过模板嵌套参数实现的;
  • 特性,策略,标签是模板编程常用技巧,它们可以是模板变得更加通用;
  • 模板甚至可以获得类型的内部信息(是否有某个 typedef),这是反射中的内省,C++ 在语言层面对反射支持很少(typeid),这不利于模板元编程;
  • 可以用递归实现伪变长参数模板,C++11 变长参数模板背后的原理也是模板递归;
  • 元容器存储元信息(如类型)、类型过滤过滤某些类型,它们是元编程的高级特性。



进一步学习

C++ 确实比较复杂,这可能是因为,虽然 C++ 语言层次比较低,但它却同时可以实现很多高级特性。进一步学习 C++ 模板元编程的途径很多:

C++ 标准库的 STL 可能是最好的学习案例,尤其是其容器、迭代器、通用算法、函数类模板等部件,实现机制很巧妙;
另外一个 C++ 库也值得一看,那就是 Boost 库,Boost 的元编程库参考文献[16];
很推荐《深入实践C++模板编程》这本书,这篇博文大量参考了这本书;
wikibooks.org 上有个介绍 C++ 各种编程技巧书:More C++ Idioms,文献[15];
文献[17]列了 C++ 模板的参考书,共四本;
好多东西,书上讲的比较浅显,而且不全面,有时候直接看 C++ 标准(最新 C++11)可能更为高效,C++ 标准并不是想象中那样难读,C++ 标准委员会网站的 Papers 也很值得看,文献[3]。


参考文献:
深入实践C++模板编程,温宇杰著,2013(到当当网);
C++程序设计语言,Bjarne Stroustrup著,裘宗燕译,2002(到当当网);
C++标准,ISO/IEC 14882:2003,ISO/IEC 14882:2011(到ISO网站,C++标准委员会);
wikipedia.org(C++, 模板, Template metaprogramming, Curiously recurring template pattern, Substitution failure is not an erro (SFINAE), Expression templates, C++11, C++14);
What does a call to 'this->template [somename]' do? (stackoverflow问答);
Advanced C++ Lessons,chapter 6,在线教程,2005(到网站);
C++ TUTORIAL - TEMPLATES - 2015,bogotobogo.com 网上教程(到网站);
C++ Templates are Turing Complete,Todd L. Veldhuizen,2003(作者网站已经停了,archive.org 保存的版本,archive.org 可能被限制浏览);
Metaprogramming in C++,Johannes Koskinen,2004(中科大老师保存的版本);
C++ Template Metaprogramming in 15ish Minutes(Stanford 课程 PPT,到网站);
Template Metaprograms,Todd Veldhuizen,1995(archive.org 保存 Todd Veldhuizen 主页,可能限制访问,在线 PS 文件转 PDF 文件网站);
Expression Templates,Todd Veldhuizen,1995;
C++ Templates as Partial Evaluation,Todd Veldhuizen,1999;
Erwin Unruh 写的第一个模板元编程程序;
wikibooks.org(C++ Programming/Templates/Template Meta-Programming,More C++ Idioms);
THE BOOST MPL LIBRARY online docs(到网站);
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

shop_da_admin

管理员

39

主题

40

帖子

247

积分
Ta的主页 发消息

网友分享更多 >

  • 机器学习的统计学知识
  • 漳州盛泰水产
  • 玉川茶家