原题如下:
试参考以下代码,完成一个static_log2,该模板类的功能是求log2(int n)的整数部分
template <int n>
class static_fact //求n的阶乘
{
public:
enum { value = static_fact<n-1>::value * n };
};
template <>
class static_fact<0>
{
public:enum { value = 1 };
};
#include <stdio.h>
void main()
{
printf(“3! = %d “, static_fact<3>::value);
}
没研究过template,连c++也不是太熟,不过看了一会,大概看出是个递归,剩下的就是想递归的结束条件了, 可怜我脑袋不太灵光,刚开始想歪了,浪费了不少时间,还好,后来还是想出来了,//blush
还有一题就是一个比较难的竞赛题了, 我的数学不好,没搞出来,哪天有空,搜一下看看怎么做的:)
本内容接上题,上题的写法是写出一个求出logk(int n)的整数部分的template,结果如下:
#include <iostream>
using namespace std;
template <int n>
class static_log2N
{
public:
enum {value = static_log2N<n/2>::value+1 };
} ;
template <>
class static_log2N<1>
{
public:
enum{value = 0};
};
int main()
{
cout<<static_log2N<28>::value<<endl;
cin.get();
}
进一步扩展,可以写出一个求出底为k,求log(int k)(int N)的整数部分的程序来,如下:
#include <iostream>
using namespace std;
template <int base,int n>
class static_logxN
{
public:
enum {value = static_logxN<base,n/base>::value+1 };
} ;
template <int base>
class static_logxN<base,1>
{
public:
enum{value = 0};
};
int main()
{
cout<<static_logxN<3,28>::value<<endl;
cin.get();
}
昨天去书店找关于此类编程的资料,在c++ templates一书中找到称其为metaprogamming, 呵呵,孤陋寡闻了, 这本书的中文版太贵了,而且网上评论说译的不是太好,于是上午就买了本影印版,看上去是有点费劲,不过可省了近20块大洋呢^_^ 趁这几天有时间,抓紧看一下:)