C++11——用于元编程的类别属性

元编程

编写一个用来编程的程序(生成代码的程序)。

以元编程来计算指数的例子:

template<int B, int N>
struct Pow {
    // 递归
    enum{ value = B*Pow<B, N-1>::value };
};

template< int B > 
struct Pow<B, 0> { 
    // 递归终止条件
    enum{ value = 1 };
};
int quartic_of_three = Pow<3, 4>::value;

类别属性 (type traits

类别属性能识别一个对象的种类和有关一个类别(class或struct)的特征。

头文件: <type_traits>

// 算法一
template< bool B > struct Algorithm {
    template<class T1, class T2> static int do_it (T1 &, T2 &)  { /*...*/ }
};

// 算法二
template<> struct Algorithm<true> {
    template<class T1, class T2> static int do_it (T1, T2)  { /*...*/ }
};

//根据给定的数据类别,从而实例化某一特定的算法
template<class T1, class T2> 
int elaborate (T1 A, T2 B) 
{
    // 若T1為int且T2為float,算法二
    // 其它情況算法一
    return Algorithm<std::is_integral<T1>::value && std::is_floating_point<T2>::value>::do_it( A, B ) ;
}

优点:代码简洁、优美。

缺点: 调试困难, 编译期的错误消息让人不知所云,运行期的调试更是困难。

posted @ 2020-06-17 17:19  elon_wang  阅读(175)  评论(0编辑  收藏  举报