一个理论解决方案(如模板应图灵完整) - 不使用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我的需求与安全无关。 –