我正在测试用户定义的文字。我想_fac
返回数字的阶乘。
让它调用一个constexpr
函数是可行的,但是它不允许我用模板来做,因为编译器抱怨参数 is not 和 cannot be constexpr
。
我对此感到困惑-文字不是常量表达式吗?5
in始终是一个可以在编译时评估的5_fac
文字,那么为什么我不能这样使用它呢?
第一种方法:
constexpr int factorial_function(int x) {
return (x > 0) ? x * factorial_function(x - 1) : 1;
}
constexpr int operator "" _fac(unsigned long long x) {
return factorial_function(x); // this works
}
第二种方法:
template <int N> struct factorial_template {
static const unsigned int value = N * factorial_template<N - 1>::value;
};
template <> struct factorial_template<0> {
static const unsigned int value = 1;
};
constexpr int operator "" _fac(unsigned long long x) {
return factorial_template<x>::value; // doesn't work - x is not a constexpr
}