模板还可以这样递归...

小楫轻舟 2011-12-24 05:49:55

#include <iostream>
using namespace std;

const unsigned P = 10;

template <unsigned P> struct test
{
static void func()
{
cout << "func: " << P << endl;
test<P - 1>().func();
}
};

struct test<0>
{
static void func()
{
cout << "func0" << endl;
}
};

int main()
{
test<P>::func();
return 0;
}
...全文
197 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
MPL基础嘛
ouyh12345 2011-12-27
  • 打赏
  • 举报
回复
学习了
failuer 2011-12-27
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 lightboat09 的回复:]
谢谢failuer的指导,学习了...
[/Quote]
呵呵,我也不怎么懂的,共同学习!



//前两天看到一个题目:不能使用乘法计算N的阶乘
//模板元实现,挺有意思的,跟大家分享一下
#include<iostream>

using namespace std;

template<int SUM, int N>
struct Mul
{
enum{val = SUM + Mul<SUM, N - 1>::val};
};

template<int SUM>
struct Mul<SUM, 1>
{
enum{val = SUM};
};

template<int N>
struct Fact
{
enum{val = Mul<Fact<N - 1>::val, N>::val};
};

template<>
struct Fact<1>
{
enum{val = 1};
};

int main()
{
cout<<Fact<10>::val<<endl;

system("pause");
return 0;
}


cbzjzsb123 2011-12-27
  • 打赏
  • 举报
回复
貌似挺實用的~
小楫轻舟 2011-12-27
  • 打赏
  • 举报
回复
谢谢failuer的指导,学习了...
failuer 2011-12-27
  • 打赏
  • 举报
回复

#include <iostream>

using namespace std;

const unsigned P = 10;

template <unsigned P>
struct test
{
static void func()
{
cout << "func: " << P << endl;
test<P - 1>::func();//这里直接使用::操作符调用就行了,没必要使用对象调用func静态成员函数了
}
};

template<>//这里应该是特化
struct test<0>
{
static void func()
{
cout << "func0" << endl;
}
};

int main()
{
test<P>::func();
return 0;
}


JV02009 2011-12-27
  • 打赏
  • 举报
回复
貌似挺實用的~
Saleayas 2011-12-26
  • 打赏
  • 举报
回复
我最早写的时候,也觉得很稀奇。
那时候,计算一个 CRC 的 函数中用的。
查表的那个静态表就是 模板生成的。
Saleayas 2011-12-26
  • 打赏
  • 举报
回复
这是 元编程 的其中的一个基础。
柯本 2011-12-26
  • 打赏
  • 举报
回复
模板,我一直很头疼的东东
ForestDB 2011-12-26
  • 打赏
  • 举报
回复
C++模板元编程,一直没看。
黯然 2011-12-24
  • 打赏
  • 举报
回复
模板...最近想开始学了..
vilnies 2011-12-24
  • 打赏
  • 举报
回复
不错,有机会也来用看看

15,440

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧