gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:25:48 25 4
gpt4 key购买 nike

我正在尝试掌握和理解可变参数模板的概念。我遇到了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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com