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,編譯時遞迴終止。這就是模板超程式設計。
廣告
資料結構
網路
關係型資料庫系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP