[問題] varadic function編譯失敗

看板C_and_CPP作者 (tortoise)時間8年前 (2017/03/21 16:53), 編輯推噓1(106)
留言7則, 3人參與, 最新討論串1/1
想寫一個最簡單的varadic function p(需不定數目的整數為參數), 把輸入的參數寫到standard out, 但是連編譯都有問題,找不到頭緒, google找到的都是varadic template,但我不想用template, 可以請大家幫忙看一下哪裡錯了嗎? (如果有違反板規麻煩告知,謝謝。) //程式碼 #include <iostream> void _real(int i) { std::cout << i << ","; } void p(int head, int... tail) { _real(head); p(tail...); } void p() {}; int main() { p(3,5,1,3,7,2); } //錯誤訊息 $ g++ -std=c++11 print.cpp print.cpp:6:25: error: expansion pattern ‘int’ contains no argument packs void p(int head, int... tail) { ^ print.cpp: In function ‘void p(int)’: print.cpp:8:7: error: ‘tail’ was not declared in this scope p(tail...); ^ print.cpp: In function ‘int main()’: print.cpp:14:18: error: no matching function for call to ‘p(int, int, int, int, int, int)’ p(3,5,1,3,7,2); ^ print.cpp:14:18: note: candidates are: print.cpp:6:6: note: void p(int) void p(int head, int... tail) { ^ print.cpp:6:6: note: candidate expects 1 argument, 6 provided print.cpp:11:6: note: void p() void p() {}; ^ print.cpp:11:6: note: candidate expects 0 arguments, 6 provided -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 106.105.12.35 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1490086381.A.C67.html

03/21 17:05, , 1F
不想用template,就只有C的va_list。那這樣何必用C++?
03/21 17:05, 1F

03/22 08:07, , 2F
我只是在學習語法想了解哪裡寫錯了,所以是沒這語法嗎
03/22 08:07, 2F

03/22 08:08, , 3F
既然c++11有varadic template,所以我猜想應該可拿掉
03/22 08:08, 3F

03/22 08:08, , 4F
template,所以試寫沒有template的版本開始,想解決問題
03/22 08:08, 4F

03/22 08:10, , 5F
還是我誤會了,c++11使用varadic一定要搭配template?
03/22 08:10, 5F

03/22 16:11, , 6F
google "variadic function"
03/22 16:11, 6F

03/22 18:31, , 7F
2種解法,一個是variadic template,一個是va_list
03/22 18:31, 7F
文章代碼(AID): #1OqEdjnd (C_and_CPP)