一個理論解決方案(如模板應圖靈完整) - 不使用constexpr功能,回落到好老std=c++0x
風格僅僅使用struct template with values
計算的。例如,不要做
constexpr uintmax_t fact(uint n) {
return n>1 ? n*fact(n-1) : (n==1 ? 1 : 0);
}
但
template <uint N> struct fact {
uintmax_t value=N*fact<N-1>::value;
}
template <> struct fact<1>
uintmax_t value=1;
}
template <> struct fact<0>
uintmax_t value=0;
}
的struct
方法是保證在編譯時專門評估。
事實上,在提升的人設法做到compile time parser是一個強烈的信號,儘管乏味,這種方法應該是可行的 - 這是一次性成本,也許人們可以認爲它是一種投資。
例如:
電源結構:
// ***Warning: note the unusual order of (power, base) for the parameters
// *** due to the default val for the base
template <unsigned long exponent, std::uintmax_t base=10>
struct pow_struct
{
private:
static constexpr uintmax_t at_half_pow=pow_struct<exponent/2, base>::value;
public:
static constexpr uintmax_t value=
at_half_pow*at_half_pow*(exponent % 2 ? base : 1)
;
};
// not necessary, but will cut the recursion one step
template <std::uintmax_t base>
struct pow_struct<1, base>
{
static constexpr uintmax_t value=base;
};
template <std::uintmax_t base>
struct pow_struct<0,base>
{
static constexpr uintmax_t value=1;
};
構建令牌
template <uint vmajor, uint vminor, uint build>
struct build_token {
constexpr uintmax_t value=
vmajor*pow_struct<9>::value
+ vminor*pow_struct<6>::value
+ build_number
;
}
一個可能的解決方案:你嚴格按照模板實現那個函數結構xyz {static constexpr long long value = ...; }'。不,實際上,我的意思是不要使用'constexpr函數',而是嚴格在結構模板中實現計算。 –
請注意,人們普遍認爲,如果知道你的算法足夠讓它被破壞,那麼你的算法就是廢話。 – immibis
對於可能遇到此問題並想嘗試的人來說,這是一個很好的一般性評論,但FWIW我的需求與安全無關。 –