c++的const和constexpr

c++有兩種常量:
一種是const:“i promise not to change this value
一種是constexpr:”to be evaluated at compile time

const 這種值可以在編譯時或是運行時賦值,但constexpr的值只能在編譯器確定

他們兩的側重點不同,就如上面英文寫的那樣
const側重於值不變;constexpr側重於編譯期就確定值

還有以下幾點是需要注意的:
如果一個constexpr變量的值來自於一個函數,那麼這個函數必須是一個constexpr
eg: constexpr int fun () {} 而且這個函數必須儘量簡單,函數體必須是一個return + 計算部分

constexpr函數也可以接受非const參數
下面的代碼是可運行的

#include <iostream>

constexpr int dfun ( int x ) {
  return x * 2;
}

int main() {
  // non-const params
  int v = 2;
  int i = dfun ( v );

  v = 1;
  i = dfun ( v );

  // const params
  constexpr int a = 2;
  int b = dfun ( a );

  std::cout << i << std::endl << b << std::endl;

  return 0;
}

常量表達式中的編譯器計算主要是因爲性能問題,在以下3種情況中,主要是因爲c++語言規則:
case標籤、模版參數、constexpr構造。

針對性能問題 不變性的概念是設計中比較重要的一部分

對於const,還是以前的理解的概念,對於constexpr,應該更多的應用於模版 泛型編程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章