C++ 模板超程式設計


當我們編寫程式使用模板在編譯時進行計算的時候,這就是模板超程式設計。

示例程式碼

#include <iostream>
using namespace std;

template<int n>struct power {
   enum { value = 4*power<n-1>::value };
};

template<>struct power<0> {
   enum { value = 1 };
};

int main() {
   cout <<”power is:”<< power<7>::value << endl;
   return 0;
}

輸出

power is:16384

在上面的示例中,當編譯器看到 power<7>::value,它嘗試建立一個 power 的例項,其中引數為 7,結果證明也必須建立 power<6>,因為列舉常量值必須在編譯時求值。對於 power<6>,編譯器需要 power<5>,依此類推。最後,編譯器使用 funStruct<1>::value,編譯時遞迴終止。這就是模板超程式設計。

更新於:2019 年 7 月 30 日

237 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.