ユーザー定義リテラルをテストしています。_fac
数値の階乗を返すようにしたい。
関数を呼び出すことはconstexpr
機能しますが、引数が ではなく、 ではないとコンパイラが不平を言うため、テンプレートでそれを行うことはできませんconstexpr
。
私はこれに混乱しています - リテラルは定数式ではありませんか? 5
in5_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
}
2 番目の方法:
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
}