c++11 可变参数模板编译失败
c++11 variadic template fail to compile
短短几行代码,希望"count"函数能给出参数个数:
#include <cstddef>
#include <utility>
using namespace std;
template<class T>
size_t f(T&& ... elem){
return sizeof...(elem);
}
int main(){
return 0;
}
但是编译失败
main.cpp:5:22: error: expansion pattern 'T&&' contains no argument packs
size_t count(T&& ... elem){
^~~~
main.cpp: In function 'size_t count()':
main.cpp:6:22: error: 'elem' has not been declared
return sizeof...(elem);
^~~~
main.cpp: In function 'int main()':
main.cpp:9:23: error: no matching function for call to 'count(int, int, int)'
return count(1,2,3);
^
main.cpp:5:8: note: candidate: 'template<class T> size_t count()'
size_t count(T&& ... elem){
^~~~~
main.cpp:5:8: note: template argument deduction/substitution failed:
main.cpp:9:23: note: candidate expects 0 arguments, 3 provided
return count(1,2,3);
^
g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
Compile, link and run...
Share!
如何解决?
你也需要用...
引入模板参数包:
template<class... T> // declares the pack "T"
// ^^^
size_t f(T&&... elem) // declares the pack "elem", uses the pack "T"
{
return sizeof...(elem); // ("sizeof..." is an operator)
}
短短几行代码,希望"count"函数能给出参数个数:
#include <cstddef>
#include <utility>
using namespace std;
template<class T>
size_t f(T&& ... elem){
return sizeof...(elem);
}
int main(){
return 0;
}
但是编译失败
main.cpp:5:22: error: expansion pattern 'T&&' contains no argument packs
size_t count(T&& ... elem){
^~~~
main.cpp: In function 'size_t count()':
main.cpp:6:22: error: 'elem' has not been declared
return sizeof...(elem);
^~~~
main.cpp: In function 'int main()':
main.cpp:9:23: error: no matching function for call to 'count(int, int, int)'
return count(1,2,3);
^
main.cpp:5:8: note: candidate: 'template<class T> size_t count()'
size_t count(T&& ... elem){
^~~~~
main.cpp:5:8: note: template argument deduction/substitution failed:
main.cpp:9:23: note: candidate expects 0 arguments, 3 provided
return count(1,2,3);
^
g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
Compile, link and run...
Share!
如何解决?
你也需要用...
引入模板参数包:
template<class... T> // declares the pack "T"
// ^^^
size_t f(T&&... elem) // declares the pack "elem", uses the pack "T"
{
return sizeof...(elem); // ("sizeof..." is an operator)
}