C++简单模板元编程

来源:互联网 发布:设计logo的软件 编辑:程序博客网 时间:2024/06/05 16:02

今天想用模板元编程,网上搜了下,很多用boost::mpl实现,我自己写了个简单测试了下:

#include <iostream>using namespace std;template <int N = 0>struct Test{Test():num(N){}int num;int arr[N];void GetNum(){printf("%d\n", num);}};int main(){Test<55> test;test.GetNum();}

模板元的优点就是在编译期把事情给确定了,但是缺点是“确定性”,运行期的好处就是“不确定性”,比如模板元编程不能这样

int main(){int num = 0;cin >> num;Test<num> test;test.GetNum();}

但是我们如果修改代码后:

#include <iostream>using namespace std;//template <int N = 0>struct Test{Test(int N):num(N){arr = new int[N];}~Test(){delete []arr;}int num;int *arr;void GetNum(){printf("%d\n", num);}};int main(){int num = 0;cin >> num;Test test(num);test.GetNum();}

副作用是我们要把本来栈上分配的数组要变成堆上动态分配,而且还要记得析构时释放内存。

0 0
原创粉丝点击