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/p/2486565.html