Bil*_*eal 14
模板无疑需要更长的时间.
但是,模板功能明显更强大,并且遵循C++语法规则,而宏则不然.
模板需要更长时间的原因是因为您可以使用递归模板,并且需要生成所有这些重复.这是构建模板元编程中的循环结构的基础.相反,宏不能自称,因此仅限于单个扩展.
例如,从维基百科无耻地窃取以下代码:
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
Run Code Online (Sandbox Code Playgroud)
注意如何在编译时计算析因,对于第一次调用(Factorial<4>),编译器需要将模板扩展5次.宏无法做到这一点.