关于模板元编程的疑问

酱油党 2012-04-17 03:55:24
如:
在编译期的函数 Func1 内部可能会调用fread等一系列函数

能否通过模板元的方式将其从运行期调整到编译期,

如果能请给予一个简单示例,如果不能,麻烦说明下理由,或者说模板元能够做到哪一步!
...全文
71 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
酱油党 2012-04-18
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 的回复:]
C/C++ code

template<int M,int N>
struct Prime_helper
{
static const int result=M%N?0:Prime_helper<M,N-1>::result;
};
template<int M>
struct Prime_helper<M,2>
{
static const int result=(M==2……
[/Quote]
你能举一个类型转换的例子吗?谢谢了
evencoming 2012-04-17
  • 打赏
  • 举报
回复
[code=C/C++]
template<int M,int N>
struct Prime_helper
{
static const int result=M%N?0:Prime_helper<M,N-1>::result;
};
template<int M>
struct Prime_helper<M,2>
{
static const int result=(M==2 || (M>2&&M%2!=0));
};
template<int M>
struct Prime
{
static const int result=Prime_helper<M,M/2+1>::result;
};
int main()
{
cout<<Prime<3>::result<<endl;
cout<<Prime<156>::result<<endl;
}
[/CODE]
oniisama 2012-04-17
  • 打赏
  • 举报
回复
不能,模板元可以做一些类型变换或数值计算,不可能调用api
evencoming 2012-04-17
  • 打赏
  • 举报
回复
不能。最多做到所谓递归求质数。

64,649

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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