【发布时间】:2015-08-11 09:43:54
【问题描述】:
我正在寻找如何使用模板来生成三角形数,一开始我写了这样的东西:
template<int i>
int f(){
return i+f<i-1>();
}
template <>
int f<1>(){
return 1;
}
printf("%d\n",f<4>());
但后来它似乎做错了什么,因为我发现它应该使用枚举来做到这一点:
template<int i>
struct f{
enum{v=i+f<i-1>::v};
};
template<>
struct f<1>{
enum{v=1};
};
printf("%d\n",f<4>::v);
我猜使用 f() 只会在编译时生成 1,2,3,4 但使用 f::v 确实会在编译时生成 10,对吗?
除此之外,还有什么不同吗?
如果我使用类属性而不是枚举:
template<int i>
struct f{
public:
int v=i+f<i-1>().v;
};
template<>
struct f<1>{
public:
int v=1;
};
printf("%d\n",f<4>().v);
,情况和使用函数类似吗?
【问题讨论】:
标签: c++ templates struct enums