模板递归中的函数、结构枚举和结构属性有什么区别?

Is there difference between function,struct enum and struct property in template recursion?

本文关键字:结构 属性 什么 区别 枚举 递归 函数      更新时间:2023-10-16

我正在寻找如何使用模板来生成三角形数,一开始我写了这样的东西:

template<int i>
int f(){
    return i+f<i-1>();
}
template <>
int f<1>(){
    return 1;
}
printf("%dn",f<4>());

但后来似乎做错了,因为我发现它应该使用enum来做:

template<int i>
struct f{
    enum{v=i+f<i-1>::v};
};
template<>
struct f<1>{
    enum{v=1};
};
printf("%dn",f<4>::v);

我猜使用f<4>()在编译时只生成1,2,3,4,但使用f<4>::v在编译时真的生成10,是这样吗?

除此之外,还有什么不同吗?

如果我用类属性代替enum:

template<int i>
struct f{
public:
    int v=i+f<i-1>().v;
};
template<>
struct f<1>{
public:
    int v=1;
};
printf("%dn",f<4>().v);

,情况类似于使用函数吗?

您的函数fstruct f的结果不能用于常量表达式,但您的变量与enum的结果可以。对于在常量表达式中使用的函数应该是constexpr int f(),它只允许在c++ 11中,struct应该是

template<int i>
struct f{
public:
    static const int v= i + f<i-1>::v;
};

启用优化后,所有这些都应该在编译时计算10

区别在于您可以对结果值做什么。函数的返回值不是常量表达式,因此不能在需要常量表达式的地方使用它。另一方面,enum值一个常量表达式。

template <int> struct Foo {};
Foo<f<4>::v> f1; // OK
Foo<f<4>()> f2;  // Compile-time error

c++ 11引入了constexpr函数(c++ 14增强了)。它们是将常量表达式作为参数给定的函数,可以返回常量表达式。如果将f声明为template <int i> constexpr int f(),则第二个Foo实例化是格式良好的。