我正在测试用户定义的字面量,我希望
让它调用一个
我对此感到困惑 - 字面量不是常量表达式吗?在
第一种方法:
_fac
返回数字的阶乘。让它调用一个
constexpr
函数是可行的,但是无法使用模板,因为编译器会抱怨参数不是 constexpr
,也不能成为 constexpr
。我对此感到困惑 - 字面量不是常量表达式吗?在
5_fac
中的 5
始终是可以在编译时评估的文字,那么为什么我不能将其作为这样使用呢?第一种方法:
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
}