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)
}
相关文章:
- 包含模板文件的递归会导致编译失败
- 提升 1.64 单元测试编译失败
- C++模板的模板编译失败
- 使用已删除的函数进行编译失败,并显示 uclibc
- MinGW-w64 编译失败,nullptr_t
- 使用提升线程时编译失败
- 编译花絮 g++, clang++, 使用 libboost -- g++8 编译失败时 g++7 成功;
- CMake + Qt,moc 编译失败,无法实现 QMetaObject 方法(编译器找不到基本 ui 对象的标头?
- 带有引用的std::tuple在clang中编译失败,但在gcc中编译失败
- 解决由于在哈希函数中使用了不完整的类型而导致的编译失败
- 将XCode升级到verison 11.1后,C++编译失败
- 添加类型名会导致程序编译失败
- 将 qi::lexeme 添加到灵气中的规则时编译失败
- 如果我在下面的代码中使用 list 而不是 vector,为什么在我尝试在迭代器之间执行减法的行中编译失败?
- 返回 std::stringstream - 编译失败
- 编译失败:strlen 不是 std 的成员
- MSBuidel - 将资源文件添加到项目后静态库编译失败
- C++ - 在 std::thread 中调用重载函数时编译失败
- QtWebEngine 到嵌入式 Linux 交叉编译失败
- 使用 glibc 2.7 包含路径编译失败