問題描述
我想知道在使用模板元編程技術時使用靜態常量和枚舉黑客有什么區別.
I'm wondering what the difference is between using a static const and an enum hack when using template metaprogramming techniques.
EX:(斐波那契通過 TMP)
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;
};
對比
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 };
};
為什么要使用一個?我已經讀到在類內部支持靜態常量之前使用了 enum hack,但為什么現在使用它?
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?
推薦答案
枚舉不是 lval,靜態成員值是,如果通過引用傳遞模板將被實例化:
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.
boost 編碼指南和舊線程 在有關該主題的 boost 檔案中.
There are some details in the boost coding guidelines and an older thread in the boost archives regarding the subject.
這篇關于模板元編程 - 使用 Enum Hack 和 Static Const 的區別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!