Re: [語法] [問題] 關於pointer of reinterpret_cast

看板C_and_CPP作者時間15年前 (2009/04/01 02:19), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串3/4 (看更多)
※ 引述《QQ29 (我愛阿蓉)》之銘言: : ※ 引述《redluna (Occlumen)》之銘言: : : 我們老師用了一個我看不懂得用法 : : template<typename T,int n> T sum(T (&a)[n]){ : : return a[0]+sum(reinterpret_cast<T(&)[n-1]>(a[1])); : : ^^^^^^^^^^^^^^^^^^^^^^^^^^^ : : } : : 我比較不懂的是這裡 : : 是不是和template的展開有關 : : T(&) 是什麼意思? : : 還是說要(&)(n)這樣讀? : : 那和T*有甚麼不同? : 你好: : 我是因為研究了你這問題 才會發那些問題文章 : 我想T(&)[]就是如推文說的 cast成陣列的 reference : 請參考這 : http://www.cnblogs.com/oomusou/archive/2007/02/09/646021.html : 問題來了 : 你這個範例compile根本過不了 : 問題出在<T(&)[n-1]> : rror C2265: 'abstract declarator' : 參考至大小為零的陣列不合法 : 改成<T(&)[n]>他就不會compile error了 : 在此想請問 : 為什麼compiler會去判斷這件事呢? : recursive不是runtime作的嘛 這邊怎麼會跑出錯誤... : 這是否可以解釋成 這種template寫法就是不能recursive? : 不管我設什麼終止條件他都是在compile time給我錯誤訊息 : 請問有人知道為什麼嘛? : 問題有點多 請各位多多指教 謝謝 改成這樣可以 compile 也可以執行: template<int n> int sum(int (&a)[n]) { return a[0]+sum(reinterpret_cast<int(&)[n-1]>(a[1])); } template<> int sum<>(int (&a)[1]) { return a[0]; } 考慮下面的 code: int a[] = {1, 2, 3, 4}; int s = sum(a); 首先會呼叫 sum<4>(), 在 sum<4>() 裡會呼叫 a[0] + sum<3>(a[1]) 以此類推, 最後到 sum<1> 時由於我們提供了specialization 版本 所以遞迴到此終止, 答案也在 compile time 求得. 至於為什麼我要把 T 拿掉改用 int 呢? 因為 c++ 規定 function template 不能 partial specialization 因此我們沒辦法寫 template<typename T> T sum<T, 1>(T (&a)[1]) { return a[0]; } 有人可能會想, 那我們就提供 function template overloading 呀 template<typename T> T sum(T (&a)[1]) { return a[0]; } 很遺憾的, 在 c++ 的 function overload resolution rules 之下 它還是會優先找到 template<typename, 1> T sum(T (&a)[1]) 這個版本 所以遞迴還是會缺乏終止條件 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.30.49 ※ 編輯: HuangTzHuan 來自: 140.112.30.49 (04/01 02:29)

04/01 02:50, , 1F
好深奧~~慢慢理解
04/01 02:50, 1F
文章代碼(AID): #19qbwjZ- (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #19qbwjZ- (C_and_CPP)