【问题标题】:C++ Templates: value should be compile-time constant but compiler says it's notC++ 模板:值应该是编译时常量,但编译器说它不是
【发布时间】:2020-07-20 10:52:39
【问题描述】:
template <const long long int lx, const long long int ly, const long long int lz, const long long int cx, const long long int cy, const long long int cz> class rtH{
  public: static const long long int sqlc=cx*cx+cy*cy+cz*cz;
static const long long int ldc=lx*cx+ly*cy+lz*cz;
};
template <const long long int lx, const long long int ly, const long long int lz, const long long int cx, const long long int cy, const long long int cz, const long long int r> class rt{
  public: static const long long int d=rtH<lx,ly,lz,cx,cy,cz>::ldc-sqrt<rtH<lx,ly,lz,cx,cy,cz>::ldc*rtH<lx,ly,lz,cx,cy,cz>::ldc-(rtH<lx,ly,lz,cx,cy,cz>::sqlc-r*r),20>::value
  ;
};
int main(){return rt<1,1,1,1,1,1,1>::d;}

编译器不会抱怨实例化 rt,因此它知道 lx,ly,lz,cx,cy,cz,r 是编译时常量。在 rtH 中,我将 sqlc 和 ldc 定义为 const。这些 const 变量只依赖于编译时常量,所以它们也应该是编译时常量,对吧?如果是这样,为什么编译器会抱怨 sqrt 的参数不是编译时常量?

注意:sqrt 可以在其他地方使用。

【问题讨论】:

  • 变量未定义为编译时常量。您需要使用constexpr 而不是const。还写const long long int 作为模板参数是荒谬的多余。写long longstd::int64_t(或写在别处using std::int64_t并将其缩短为int64_t)。
  • const 只是表示程序不可修改,并不意味着“编译时”。 constexpr 是一个不同的关键字,当应用于变量时,它意味着编译时常量。
  • @ZuodianHu 将其作为答案发布

标签: c++ templates tmp


【解决方案1】:

const 仅表示程序不可修改,并不以任何方式暗示编译时。 constexpr 是一个不同的关键字,当应用于变量时,它意味着编译时常量。

【讨论】:

    【解决方案2】:

    原来问题不在于编译器的无能;我在表达式的一部分中溢出,标准明确包括有符号溢出作为表达式不是常量的条件。

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2012-07-31
      • 2011-09-02
      • 1970-01-01
      相关资源
      最近更新 更多