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

[复制链接]
10031|89
 楼主| elecintop 发表于 2015-3-24 21:16 | 显示全部楼层
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) { }
 楼主| elecintop 发表于 2015-3-24 21:17 | 显示全部楼层
对循环次数固定且比较小的循环语句,对其进行展开并内联可以避免函数调用以及执行循环语句中的分支,从而可以提高性能,对上述代码做如下测试,代码在 VS2013 的 Release 下编译运行:
  1. #include <iostream>
  2. #include <omp.h>
  3. #include <string.h> // memcpy

  4. int main() {
  5.     double t1, t2, t3; const int num=100000000;
  6.     int data[4]; int inidata[4]={3,4,2,1};
  7.     t1 = omp_get_wtime();
  8.     for(int i=0; i<num; ++i) { memcpy(data, inidata, 4); bubbleSort(data, 4); }
  9.     t1 = omp_get_wtime()-t1;
  10.     t2 = omp_get_wtime();
  11.     for(int i=0; i<num; ++i) { memcpy(data, inidata, 4); bubbleSort4(data); }
  12.     t2 = omp_get_wtime()-t2;
  13.     t3 = omp_get_wtime();
  14.     for(int i=0; i<num; ++i) { memcpy(data, inidata, 4); IntBubbleSort<4>(data); }
  15.     t3 = omp_get_wtime()-t3;
  16.     std::cout << t1/t3 << '\t' << t2/t3 << '\n';
  17.     std::cin.get(); return 0;
  18. }

  1. 2.38643 0.926521
 楼主| elecintop 发表于 2015-3-24 21:17 | 显示全部楼层
上述结果表明,模板元编程实现的循环展开能够达到和手动循环展开相近的性能(90% 以上),并且性能是循环版本的 2 倍多(如果扣除 memcpy 函数占据的部分加速比将更高,根据 Amdahl 定律)。这里可能有人会想,既然循环次数固定,为什么不直接手动循环展开呢,难道就为了使用模板吗?当然不是,有时候循环次数确实是编译期固定值,但对用户并不是固定的,比如要实现数学上向量计算的类,因为可能是 2、3、4 维,所以写成模板,把维度作为 int 型模板参数,这时因为不知道具体是几维的也就不得不用循环,不过因为维度信息在模板实例化时是编译期常量且较小,所以编译器很可能在代码优化时进行循环展开,但我们想让这一切发生的更可控一些。
 楼主| elecintop 发表于 2015-3-24 21:18 | 显示全部楼层
上面用三个函数模板 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. }
 楼主| elecintop 发表于 2015-3-24 21:18 | 显示全部楼层
上面代码看似很好,不仅整合了代码,借助类成员的访问控制,还隐藏了实现细节。不过它存在着很大问题,如果实例化 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),如果编译器确实内联展开代码则不会导致代码膨胀(除了循环展开本身会带来的代码膨胀),但因为重复编译原本可以复用的模板实例,会增加编译时间。在上一节的例子中,因为只涉及编译期常量计算,并不涉及函数(函数模板,或类模板的成员函数,函数被编译成具体的机器二进制代码),并不会出现代码膨胀。
 楼主| elecintop 发表于 2015-3-24 21:18 | 显示全部楼层
为了清晰证明上面的论述,我们去掉所有 inline 并将函数实现放到类外面(类里面实现的成员函数都是内联的,因为函数实现可能被包含多次,见文献[2] 10.2.9,不过现在的编译器优化能力很强,很多时候加不加 inline 并不影响编译器自己对内联的选择…),分别编译分散版本和类模板封装版本的冒泡排序代码编译生成的目标文件(VS2013 下是 .obj 文件)的大小,代码均在 VS2013 Debug 模式下编译(防止编译器优化),比较 main.obj (源文件是 main.cpp)大小。
 楼主| elecintop 发表于 2015-3-24 21:19 | 显示全部楼层
类模板封装版本代码如下,注意将成员函数在外面定义的写法:
  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. }
 楼主| elecintop 发表于 2015-3-24 21:19 | 显示全部楼层
分散定义函数模板版本代码如下,为了更具可比性,也将函数放在类里面作为成员函数:
  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. }
 楼主| elecintop 发表于 2015-3-24 21:20 | 显示全部楼层
程序中条件编译都未打开时(#if 0),main.obj 大小分别为 264 KB 和 211 KB,条件编译打开时(#if 1),main.obj 大小分别为 1073 KB 和 620 KB。可以看到,类模板封装版的对象文件不但绝对大小更大,而且增长更快,这和之前分析是一致的。
 楼主| elecintop 发表于 2015-3-24 21:20 | 显示全部楼层
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
 楼主| elecintop 发表于 2015-3-24 21:21 | 显示全部楼层
代码有点长(我已经尽量压缩行数),请先看最下面的 main() 函数,表达式模板允许我们以 “-x / sqrt( 1.0 + x )” 这种类似数学表达式的方式传参数,在 evaluate() 内部,将 0-10 的数依次赋给自变量 x 对表达式进行求值,这是通过在 template<> DExpr 类模板内部重载 operator() 实现的。我们来看看这一切是如何发生的。
 楼主| elecintop 发表于 2015-3-24 21:21 | 显示全部楼层
在 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() 表达式求值。
 楼主| elecintop 发表于 2015-3-24 21:21 | 显示全部楼层

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

×
 楼主| elecintop 发表于 2015-3-24 21:22 | 显示全部楼层
上面代码函数实现写在类的内部,即内联,如果编译器对内联支持的好的话,上面代码几乎等价于如下代码:
  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
 楼主| elecintop 发表于 2015-3-24 21:23 | 显示全部楼层
和表达式模板类似的技术还可以用到向量计算中,以避免产生临时向量变量,见文献[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;
 楼主| elecintop 发表于 2015-3-24 21:23 | 显示全部楼层
模板代码实现向量计算如下:
  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. }
 楼主| elecintop 发表于 2015-3-24 21:23 | 显示全部楼层
不过值得一提的是,传统代码可以用 C++11 的右值引用提升性能,C++11 新特性我们以后再详细讨论。
 楼主| elecintop 发表于 2015-3-24 21:24 | 显示全部楼层
我们这里看下文献[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. };
 楼主| elecintop 发表于 2015-3-24 21:24 | 显示全部楼层
简化后(向量长度固定为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. }
 楼主| elecintop 发表于 2015-3-24 21:25 | 显示全部楼层
alpha*(u – v)” 的类型推断过程如下图所示,其中有子类到基类的隐式类型转换:

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

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

本版积分规则

快速回复 在线客服 返回列表 返回顶部