c++ - 可变参数模板示例未编译

标签 c++ templates c++11

我正在尝试掌握和理解可变参数模板的概念。 我遇到了this例子

#include <iostream>
using namespace std;

//Output function to output any type without type specifiers like printf() family
template <typename T, typename ...P>
void output(T t, P ...p)
{
  cout << t << ' ';
  if (sizeof...(p)) { output(p...); }
  else { cout << '\n'; }
}

//Since variadic templates are recursive, must have a base case
void output() { cout << "\n"; }

//Test it
int main()
{
  //output();
  output('5', 2);

  return(0);
}

但是当我尝试运行它时出现错误

main.cpp: In instantiation of 'void output(T, P ...) [with T = int; P = {}]':
main.cpp:10:29:   required from 'void output(T, P ...) [with T = char; P = {int}]'
main.cpp:21:16:   required from here
main.cpp:10:29: error: no matching function for call to 'output()'
   if (sizeof...(p)) { output(p...); }
                             ^
main.cpp:7:6: note: candidate: template<class T, class ... P> void output(T, P ...)
 void output(T t, P ...p)
      ^
main.cpp:7:6: note:   template argument deduction/substitution failed:
main.cpp:10:29: note:   candidate expects at least 1 argument, 0 provided
   if (sizeof...(p)) { output(p...); }
                             ^

关于如何修复它的任何建议。谢谢

最佳答案

切换输出函数的声明顺序:

//Since variadic templates are recursive, must have a base case
void output() { cout << "\n"; }

//Output function to output any type without type specifiers like printf() family
template <typename T, typename ...P>
void output(T t, P ...p)
{
  cout << t << ' ';
  if (sizeof...(p)) { output(p...); }
  else { cout << '\n'; }
}

对于模板函数,重载解析规则变得很古怪,因此编译器只考虑到目前为止已声明的重载,而没有考虑您的非模板。当编写多个重载时,其中一个或多个是模板函数,声明顺序很重要。

关于c++ - 可变参数模板示例未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36488500/

相关文章:

c++ - C++ 完整性测试生成器列表?

c++ - 两个 C++ 应用程序在 Linux 上共享一个只读内存区域

templates - thymeleaf :text - Put a text without removing HTML structures

c++ - 我可以在超出范围后保留 vector 数据吗

c++ - 为整数类型重载运算符 ^

html - amp-carousel 的下一张和上一张图像箭头错位

C++构造函数中的通用引用和返回值优化(rvo)

c++ - 对 std::unordered_map::reserve 的不必要或冗余调用的行为

c++ - 为什么 "universal references"具有与右值引用相同的语法?

c++ - std::unordered_map 插入错误