错误!Constexpr变量必须通过常数表达式constexpr初始化

Error! constexpr variable must be initialized by a constant expression constexpr

本文关键字:常数 表达式 constexpr 初始化 Constexpr 变量 错误      更新时间:2023-10-16
// The constant base "a" that is being used to compute f_{ut}.
constexpr float A_CONST = 6.76;
// The max number of ratings by any given user on a given date. This
// was found by create_f_u_t.py.
constexpr int MAX_NUM_RAT_USER_DATE = 2651;
// The maximum possible value for f_{ut} is the floor of the log base
// "a" of the maximum number of ratings by any user on a given date.
auto BB = std::floor(std::log(MAX_NUM_RAT_USER_DATE)/std::log(A_CONST));

constexpr int MAX_F_U_T = BB;

它给了我错误!当我编译时,它

说:错误:constexpr变量'max_f_u_t'必须由一个初始化 恒定表达 constexpr int max_f_u_t = bb;

您可以在GCC中获得std::floorstd::logconstexpr版本,但我认为它不是ISO C 。也不要忘记将BB也是constexpr

#include <cmath>
int main()
{
  // The constant base "a" that is being used to compute f_{ut}.
  constexpr float A_CONST = 6.76;
  // The max number of ratings by any given user on a given date. This
  // was found by create_f_u_t.py.
  constexpr int MAX_NUM_RAT_USER_DATE = 2651;
  // The maximum possible value for f_{ut} is the floor of the log base
  // "a" of the maximum number of ratings by any user on a given date.
  constexpr auto BB = std::floor(std::log(MAX_NUM_RAT_USER_DATE)/std::log(A_CONST));
  constexpr int MAX_F_U_T = BB;
}

wandbox上的演示

constexpr变量必须满足以下要求:

  • 它的类型必须是文字类型。
  • 必须立即初始化
  • 其初始化的全表达,包括所有隐式转换,构造函数呼叫等,必须是恒定的表达式

检查constexpr以获取更多详细信息