簡體   English   中英

C++ 模板:值應該是編譯時常量,但編譯器說不是

[英]C++ Templates: value should be compile-time constant but compiler says it's not

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<> 在其他地方有效。

const只是意味着程序不可修改,並不意味着編譯時以任何方式。 constexpr是一個不同的關鍵字,當應用於變量時,它意味着編譯時常量。

事實證明,問題不在於編譯器的無能; 我在表達式的一部分中溢出,標准明確包括有符號溢出作為表達式不恆定的條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM