[問題] template + 不定參數

看板C_and_CPP (C/C++)作者 (閉上眼的魚)時間14年前 (2012/04/04 22:18), 編輯推噓3(3010)
留言13則, 5人參與, 最新討論串1/1
一份不定參數之 template 原始碼如下 // for pod template<typename Type> Type sum(size_t n, ...) { va_list pa; Type sum = static_cast<Type>(0); va_start(pa, n); while(n--) sum += va_arg(pa, Type); va_end(pa); return sum; } int main() { cout << "correct:" << sum<unsigned> (2, 1, 2) << endl; cout << "error :" << sum<int> (2, 1.0, 2.0) << endl; cout << "correct:" << sum<double> (2, 1.0, 2.0) << endl; cout << "error :" << sum<float> (2, 1.0f, 2.0f) << endl; cin.get(); return 0; } main 前三行都在意料之中,我納悶的是為何第四行出來的結果是錯的? sum<float> (2, 1.0f , 2.0f) 最後會傳回 1.875,不知是否我誤會了什麼? -- If there is no tomorrow, I want to see u last time. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 180.177.76.161 ※ 編輯: EdisonX 來自: 180.177.76.161 (04/04 22:20)

04/04 22:34, , 1F
不定參數會 default argument promotion
04/04 22:34, 1F

04/04 22:34, , 2F
所以 float 會用 double 傳
04/04 22:34, 2F

04/04 22:38, , 3F
謝謝H大,請教是否有技巧(如特偏化)使sum<float>正常使用?
04/04 22:38, 3F

04/04 23:05, , 4F
04/04 23:05, 4F

04/04 23:10, , 5F
QQ 你寫的是 C++ 嗎? http://bit.ly/HkOjvt
04/04 23:10, 5F

04/04 23:17, , 6F
奇怪,vc2010 跑起來都有問題,請教是否該安裝哪些額外 lib
04/04 23:17, 6F

04/04 23:17, , 7F
或是換 compiler ?
04/04 23:17, 7F

04/04 23:18, , 8F

04/04 23:19, , 9F
gcc 4.4 以上
04/04 23:19, 9F

04/04 23:30, , 10F
可跑了, 謝謝 A 大與 L 大
04/04 23:30, 10F

04/04 23:41, , 11F
http://codepad.org/3oPEfPnz 只會寫簡單的,亂浪費記憶體
04/04 23:41, 11F

04/04 23:43, , 12F
p大讓我想到字串相加 LOL
04/04 23:43, 12F

04/05 00:15, , 13F
p 大的方法竟然沒想到!感謝提供。
04/05 00:15, 13F
文章代碼(AID): #1FV5WWGp (C_and_CPP)
文章代碼(AID): #1FV5WWGp (C_and_CPP)