作者tortoise (tortoise)
看板C_and_CPP
標題[問題] varadic function編譯失敗
時間Tue Mar 21 16:52:59 2017
想寫一個最簡單的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
→ Caesar08: 不想用template,就只有C的va_list。那這樣何必用C++? 03/21 17:05
→ tortoise: 我只是在學習語法想了解哪裡寫錯了,所以是沒這語法嗎 03/22 08:07
→ tortoise: 既然c++11有varadic template,所以我猜想應該可拿掉 03/22 08:08
→ tortoise: template,所以試寫沒有template的版本開始,想解決問題 03/22 08:08
→ tortoise: 還是我誤會了,c++11使用varadic一定要搭配template? 03/22 08:10
推 Sidney0503: google "variadic function" 03/22 16:11
→ Caesar08: 2種解法,一個是variadic template,一個是va_list 03/22 18:31