C++ Template Metaprogramming.Chapter 1

元程序(metaprogram)

Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at runtime.

所谓元编程就是说写出的程序是用来写程序或者控制程序的,或者在编译时而不是运行时做一些工作。所以各种code generation的工具、C#或者Java中的反射,C++中的Template 等都是元编程。下面是一个小例子:

#!/bin/bash
# metaprogram
echo '#!/bin/bash' >program
for ((I=1; I<=992; I++))  do
echo "echo $I" >>program
done
chmod +x program 

 

在C++中使用元编程进行数值计算

题目: 将无符号的十进制数值转换为等价的二进制指,比如2,转换为10;10转换为1010。

template <unsigned  long N>
struct binary
{
     static unsigned  const value
       = binary<N/ 10>::value <<  1    //  prepend higher bits
         | N% 10;                     //  to lowest bit
};
 
template <>                            //  specialization
struct binary< 0>                       //  terminates recursion
{
     static unsigned  const value =  0;
};
 
unsigned  const one   =    binary< 1>::value;
unsigned  const three =   binary< 11>::value;
unsigned  const five  =  binary< 101>::value;
unsigned  const seven =  binary< 111>::value;
unsigned  const nine  = binary< 1001>::value;

 

这个程序很类似递归函数,而当N为0时是整个调用的结束条件,这里是用特化版的模版来实现的。下面我们来看看runtime版的递归实现:

unsigned binary(unsigned  long N)
{
     return N ==  0 ?  0 : N% 10 +  2 * binary(N/ 10);
}

 

下面是runtime版的迭代实现:

   unsigned binary(unsigned  long N)
   {
       unsigned result =  0;
        for (unsigned bit =  0x1; N; N /=  10, bit <<=  1)
       {
            if (N% 10)
               result += bit;
       }
        return result;
   }

 

迭代版在run time时往往效率更高。 但是在C++元程序中,递归是常用方法。

C++在compile time部分通常称为“纯函数性语言(pure functional language)”,因为它有个特性:元数据是不可变的(immutable),并且元函数没有副作用。导致compile time的C++没有任何与用于runtime C++中非常量相对应的东西。由于无法在不检查其终结条件中一些可变东西的状态,因此在编译器无法实现迭代。在C++元程序中,递归是常用方法。


在C++中使用元编程进行类型计算

元编程的主要内容,后续会慢慢展开。

转载于:https://www.cnblogs.com/whyandinside/archive/2012/05/06/2486565.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值