本文介绍了模板元编程 - 使用枚举黑客和静态const之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想知道在使用模板元编程技术时使用静态const和枚举hack之间的区别是什么。 EX:(Fibonacci via TMP) p> template< int n> struct TMPFib { static const int val = TMPFib< n-1> val + TMPFib :: val; }; 模板<> struct TMPFib< 1。 { static const int val = 1; }; 模板<> struct TMPFib< 0> { static const int val = 0; }; vs code> template< int n> struct TMPFib { enum { val = TMPFib< n-1> val + TMPFib }; }; 模板<> struct TMPFib< 1。 { enum {val = 1}; }; 模板<> struct TMPFib< 0> { enum {val = 0}; }; 为什么要使用一个?我已经读过枚举hack是在类中支持static const之前使用的,但为什么要使用它呢?解决方案不是lvals,静态成员值是,如果通过引用传递,模板将被实例化: void f(const int& ); f(TMPFib 1 :: value); 如果你想做纯编译时计算等,这是一个不良的副作用。 p> 主要的历史区别是,枚举也适用于不支持成员值的类初始化的编译器,这应该在大多数编译器中固定。 枚举和静态常量之间的编译速度也可能不同。 boost编码指南和旧版本线程关于主题的升级档案。 I'm wondering what the difference is between using a static const and an enum hack when using template metaprogramming techniques.EX: (Fibonacci via TMP)template< int n > struct TMPFib { static const int val = TMPFib< n-1 >::val + TMPFib< n-2 >::val;};template<> struct TMPFib< 1 > { static const int val = 1;};template<> struct TMPFib< 0 > { static const int val = 0;};vs.template< int n > struct TMPFib { enum { val = TMPFib< n-1 >::val + TMPFib< n-2 >::val };};template<> struct TMPFib< 1 > { enum { val = 1 };};template<> struct TMPFib< 0 > { enum { val = 0 };};Why use one over the other? I've read that the enum hack was used before static const was supported inside classes, but why use it now? 解决方案 Enums aren't lvals, static member values are and if passed by reference the template will be instanciated:void f(const int&);f(TMPFib<1>::value);If you want to do pure compile time calculations etc. this is an undesired side-effect.The main historic difference is that enums also work for compilers where in-class-initialization of member values is not supported, this should be fixed in most compilers now.There may also be differences in compilation speed between enum and static consts.There are some details in the boost coding guidelines and an older thread in the boost archives regarding the subject. 这篇关于模板元编程 - 使用枚举黑客和静态const之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-28 09:02