【问题标题】:Is there difference between function,struct enum and struct property in template recursion?模板递归中的函数,结构枚举和结构属性之间有区别吗?
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      启用优化后,所有这些都应在编译时计算 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 &lt;int i&gt; constexpr int f(),则第二个Foo 实例是格式正确的。

      【讨论】:

        猜你喜欢
        • 2016-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多