您的位置:首页 > 编程语言 > C语言/C++

c++模版元编程

2015-09-04 11:58 477 查看
编译时计算阶乘

#include<iostream>

using namespace std;
template<int n>
class Factorial{
public:
enum{ value = n * Factorial<n-1>::value };
};
template<>
class Factorial<1>{
public:
enum{ value = 1 };
};

int main()
{
cout << Factorial<5>::value << endl;
system("pause");
return 0;
}


编译时展开循环

#include<iostream>

using namespace std;

template<int n, class Function>
class loop{
public:
static void Do(Function fun)
{
loop<n - 1, Function>::Do(fun);
fun(n);
}
};
template<class Function>
class loop<-1, Function>{
public:
static void Do(Function fun){}
};
void work(int i)
{
cout << "work " << i << endl;
}
int main()
{
loop<5, decltype(work)>::Do(work);
system("pause");
return 0;
}

利用c++的模版特性,使得我们在编译的时候可以做很多事情,比如编译时可以确定变量的类型,数量等等

更多用法可以参考loki库的实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++