用户定义的文字参数不是constexpr

User defined literal arguments are not constexpr?

本文关键字:constexpr 参数 文字 定义 用户      更新时间:2023-10-16

我正在测试用户定义的文字。我想让_fac返回这个数的阶乘

让它调用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
}

我不知道在c++ 11中是否有比当前接受的答案更好的方法来做到这一点,但是在c++ 14中使用宽松的constexpr,您可以编写"正常"代码:

constexpr unsigned long long int operator "" _fac(unsigned long long int x) {
    unsigned long long int result = 1;
    for (; x >= 2; --x) {
        result *= x;
    }
    return result;
}
static_assert(5_fac == 120, "!");

我是这样做的:

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

非常感谢KerrekSB!

我可能错了,但我认为constexpr函数也可以用非常量参数调用(在这种情况下,它们不给出常量表达式,并在运行时进行评估)。这对于非类型模板参数就不太管用了。

为了使用constexpr和用户定义的字面值,显然必须使用可变的模板。请查看wikipedia文章中的第二个清单作为示例。

@Pubby。消化char非类型参数包的简单方法是将其包含到字符串的初始化列表中。然后你可以使用atoi, atof等:

#include <iostream>
template<char... Chars>
  int
  operator "" _suffix()
  {
    const char str[]{Chars..., ''};
    return atoi(str);
  }
int
main()
{
  std::cout << 12345_suffix << std::endl;
}

记住为c风格的函数附加一个空字符。