User defined literal arguments are not constexpr?

Posted by Pubby on Stack Overflow See other posts from Stack Overflow or by Pubby
Published on 2011-11-12T23:52:25Z Indexed on 2011/11/13 1:50 UTC
Read the original article Hit count: 244

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, however it doesn't let me do it with templates as the compiler complains that the arguments are not and cannot be constexpr.

I'm confused by this - aren't literals constant expressions? The 5 in 5_fac is always a literal that can be evaluated during compile time, so why can't I use it as such?

First method:

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
}

Second method:

template <int N> struct factorial {
  static const unsigned int value = N * factorial<N - 1>::value;
};
template <> struct factorial<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
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about c++11