万企互联-专注高端网站建设
扫描关注万企互联微信公众账号

扫一扫微信二维码

C++模板元编程

程序设计2012/2/3 969

摘要

  本文描述了模板元编程

  摘要

  本文描述了模板元编程技术的起源、概念和机制,并介绍了模板元编程技术在Blitz++和Loki程序库中的应用。

  关键字

  编译期计算 模板元编程 Blitz++ Loki

  导言

  1994年,C++标准委员会在圣迭哥举行的一次会议期间Erwin Unruh展示了一段可以产生质数的代码。这段代码的特别之处在于质数产生于编译期而非运行期,在编译器产生的一系列错误信息中间夹杂着从2到某个设定值之间的所有质数:

// Prime number computation by Erwin Unruh
template <int i> struct D { D(void*); operator int(); };
template <int p, int i> struct is_prime {
  enum { prim = (p%i) && is_prime<(i > 2 ? p : 0), i -1> :: prim };
};
template < int i > struct Prime_print {
  Prime_print<i-1> a;
  enum { prim = is_prime<i, i-1>::prim };
  void f() { D<i> d = prim; }
};
struct is_prime<0,0> { enum {prim=1}; };
struct is_prime<0,1> { enum {prim=1}; };
struct Prime_print<2> { enum {prim = 1}; void f() { D<2> d = prim; } };
#ifndef LAST
#define LAST 10
#endif
main () {
  Prime_print<LAST> a;
} 
  类模板D只有一个参数为void*的构造器,而只有0才能被合法转换为void*。1994年,Erwin Unruh采用Metaware 编译器编译出错信息如下(以及其它一些信息,简短起见,它们被删除了):

  | Type `enum{}′ can′t be converted to txpe `D<2>′ ("primes.cpp",L2/C25).

  | Type `enum{}′ can′t be converted to txpe `D<3>′ ("primes.cpp",L2/C25).

  | Type `enum{}′ can′t be converted to txpe `D<5>′ ("primes.cpp",L2/C25).

  | Type `enum{}′ can′t be converted to txpe `D<7>′ ("primes.cpp",L2/C25).

  如今,上面的代码已经不再是合法的C++程序了。以下是Erwin Unruh亲手给出的修订版,可以在今天符合标准的C++编译器上进行编译:

// Prime number computation by Erwin Unruh
template <int i> struct D { D(void*); operator int(); };
template <int p, int i> struct is_prime {
  enum { prim = (p==2) || (p%i) && is_prime<(i>2?p:0), i-1> :: prim };
};
template <int i> struct Prime_print {
Prime_print<i-1> a;
  enum { prim = is_prime<i, i-1>::prim };
  void f() { D<i> d = prim ? 1 : 0; a.f();}
};
template<> struct is_prime<0,0> { enum {prim=1}; };
template<> struct is_prime<0,1> { enum {prim=1}; };
template<> struct Prime_print<1> {
  enum {prim=0};
  void f() { D<1> d = prim ? 1 : 0; };
};
#ifndef LAST
#define LAST 18
#endif
main() {
  Prime_print<LAST> a;
  a.f();
} 
  在GNU C++ (MinGW Special) 3.2中编译这段程序时,编译器将会给出如下出错信息(以及其它一些信息,简短起见,它们被删除了):


 

文章分类
程序设计
打开微信,点击底部的“发现”,使用“扫一扫”即可将网页分享至朋友圈。
万企互联 咸阳网站建设 咸阳微信营销 IDC主机测评 IP地址查询 万企工具 四六互联 四六技术网 超越彼岸BEYOND 六佰号 秦川云 秦川云影院