本帖最后由 不死鸟之翼 于 2018-4-2 23:16 编辑  
 
 
倒不太一样…这个是C++14的特性,叫Variadic templates 不过打包模板参数也确实是编译期展开的 
一般我用这个做类型安全的printf 大概是这样(用Win32API写屏的) 
 
重载了operator<<(ostream&)的类型都能写进去 比如各种矩阵类)好像暴露了什么 
 
template<typename T> void print(const T& arg) {         wstringstream ss;         ss << arg;         HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);         DWORD charsWritten;         wstring str = ss.str();         WriteConsoleW(hStdOut, str.c_str(), str.size(), &charsWritten, NULL); }   template<typename T1, typename T2, typename... Ts> void print(const T1& arg1, const T2& arg2, Ts... rest) {         wstringstream ss;         ss << arg1 << arg2;         print(ss.str(), rest...); }   int main() {         print(L"这是", 1, L"个类型安全的", L"printf\n"); } 
 
 template<typename T>  
void print(const T& arg) {  
        wstringstream ss;  
        ss << arg;  
        HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);  
        DWORD charsWritten;  
        wstring str = ss.str();  
        WriteConsoleW(hStdOut, str.c_str(), str.size(), &charsWritten, NULL);  
}  
   
template<typename T1, typename T2, typename... Ts>  
void print(const T1& arg1, const T2& arg2, Ts... rest) {  
        wstringstream ss;  
        ss << arg1 << arg2;  
        print(ss.str(), rest...);  
}  
   
int main() {  
        print(L"这是", 1, L"个类型安全的", L"printf\n");  
}  
 
  
 
 
 
 
  
 
正经的TMP算斐波那契数列的话大概是这样 
 
template<int N> struct Fibonacci {         enum { value = Fibonacci<N - 2>::value + Fibonacci<N - 1>::value }; };   template<> struct Fibonacci<1> {         enum { value = 1 }; };   template<> struct Fibonacci<2> {         enum { value = 1 }; };   int main() {         cout << Fibonacci<5>::value << endl; } 
 
 template<int N>  
struct Fibonacci {  
        enum { value = Fibonacci<N - 2>::value + Fibonacci<N - 1>::value };  
};  
   
template<>  
struct Fibonacci<1> {  
        enum { value = 1 };  
};  
   
template<>  
struct Fibonacci<2> {  
        enum { value = 1 };  
};  
   
int main() {  
        cout << Fibonacci<5>::value << endl;  
}  
 
  
 
给两个特化就行了)没有constexpr的时代就是这么简单暴力 |