模板递归中的函数、结构枚举和结构属性有什么区别?
Is there difference between function,struct enum and struct property in template recursion?
我正在寻找如何使用模板来生成三角形数,一开始我写了这样的东西:
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);
,情况类似于使用函数吗?
您的函数f
和struct 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
实例化是格式良好的。
相关文章:
- C++概念:如何使用'concept'检查模板化结构的属性?
- "perf_event_attr"结构的"read_format"属性的选项到底是什么?
- 使用内存地址访问结构的属性值
- 通过指针算法调用结构的结构属性
- 无法在 unordered_set 中找到 () 结构属性
- 嵌套结构属性继承
- 在C++中循环数组时访问结构属性
- 为什么结构属性声明和初始化顺序的行为是这样的?
- gcc 显示结构属性为 0,但 clang 显示不同的值
- 使用 Spirit 将 std::vector<std::vector<double> 解析为结构属性
- 如何使用索引访问C 结构属性值
- 从外部函数访问外部结构属性
- 如何在C++中将结构属性转换为指针引用
- 如何通过字符串名称访问结构属性
- 提升灵气自定义句法属性(通过语义动作设置结构属性的特定成员)
- boost::spirit::qi具有相同的简单自适应结构属性的规则会导致编译错误
- 结构属性操作符重载
- 读取int*类型的结构属性值时遇到问题
- 模板递归中的函数、结构枚举和结构属性有什么区别?
- 在 C 中,除了使用 val 之外,不能更改结构属性 #define