模板递归中的函数,结构枚举和结构属性之间是否存在差异?

时间:2015-08-11 09:43:54

标签: c++ templates struct enums

我发现如何使用模板生成三角形数字,在开始时我写了类似的内容:

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&lt; 4&gt;()只在编译时生成1,2,3,4但是在编译时使用f&lt; 4&gt; :: v确实生成了10,是吗?

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

此外,如果我使用class属性而不是enum:

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);

,是否与使用函数类似?

2 个答案:

答案 0 :(得分:0)

您的函数fstruct f的结果不能用于常量表达式,但是带有枚举的变量的结果可以。对于在常量表达式函数中使用应该是 constexpr int f()并且只允许在C ++ 11中使用,struct应该是

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

答案 1 :(得分:0)

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

不同之处在于您可以对结果值做些什么。函数的返回值不是常量表达式,因此在需要常量表达式的情况下不能使用它。另一方面,枚举值常量表达式。

template <int> struct Foo {};

Foo<f<4>::v> f1; // OK
Foo<f<4>()> f2;  // Compile-time error

引入了C ++ 11(和C ++ 14缓存)constexpr函数。它们是函数,给定常量表达式作为参数,可以返回常量表达式。如果您将f声明为template <int i> constexpr int f(),则第二个Foo实例的格式正确。