User defined literal arguments are not constexpr?

后端 未结 5 1094
余生分开走
余生分开走 2021-01-01 11:43

I\'m testing out user defined literals. I want to make _fac return the factorial of the number.

Having it call a constexpr function works,

5条回答
  •  余生分开走
    2021-01-01 12:15

    This is how I ended up doing it:

    template 
    constexpr t pow(t base, int exp) {
      return (exp > 0) ? base * pow(base, exp-1) : 1;
    };
    
    template  struct literal;
    template <> struct literal<> {
      static const unsigned int to_int = 0;
    };
    template  struct literal {
      static const unsigned int to_int = (c - '0') * pow(10, sizeof...(cv)) + literal::to_int;
    };
    
    template  struct factorial {
      static const unsigned int value = N * factorial::value;
    };
    template <> struct factorial<0> {
      static const unsigned int value = 1;
    };
    
    template 
    constexpr unsigned int operator "" _fac()
    {
      return factorial::to_int>::value;
    }
    

    Huge thanks to KerrekSB!

提交回复
热议问题