gpt4 book ai didi

c++ - 编译器对模板的无效实例化给出错误

转载 作者:行者123 更新时间:2023-12-02 18:42:30 26 4
gpt4 key购买 nike

#include<iostream>
template<typename T, typename... Rest>
void printf_vt( const char *s, T value,Rest... rest)
{

while (*s) {
if (*s == '%' && *(++s) != '%') {
std::cout << value;
printf_vt(s, rest...); //called even when *s is 0,
return; //but does nothing in that case
}
std::cout << *s++;
}
}

int main() {
int x = 10;
float y = 3.6;
const char* msg2 = "can accept % parameters (or %); x=%,y=%\n";
printf_vt(msg2, 100, "more",x,y);
return 0;
}

模仿“C”printf函数的程序(与问题无关)。

错误:

t1.cpp: In instantiation of 'void printf_vt(const char*, T, Rest ...) [with T = float; Rest = {}]':
t1.cpp:281:12: recursively required from 'void printf_vt(const char*, T, Rest ...) [with T = const char*; Rest = {int, float}]'
t1.cpp:281:12: required from 'void printf_vt(const char*, T, Rest ...) [with T = int; Rest = {const char*, int, float}]'
t1.cpp:293:11: required from here
t1.cpp:281:26: error: no matching function for call to 'printf_vt(const char*&)'
281 | printf_vt(s, rest...); //called even when *s is 0,
| ~~~~~~~~~^~~~~~~~~~~~
t1.cpp:275:6: note: candidate: 'template<class T, class ... Rest> void printf_vt(const char*, T, Rest ...)'
275 | void printf_vt( const char *s, T value,Rest... rest)
| ^~~~~~~~~
t1.cpp:275:6: note: template argument deduction/substitution failed:
t1.cpp:281:26: note: candidate expects at least 2 arguments, 1 provided
281 | printf_vt(s, rest...);
| ~~~~~~~~~^~~~~~~~~~~~

问题是编译器正在尝试使用创建模板函数

Rest = {int , const char*, int , float}  //{100 , "more" , x , y}

为什么要这样做?当有 2 个必需参数时,编译器不应使用 100 作为可变参数。

它还会尝试使用 Rest = {const char* , int , const char* ,int , float} 创建模板函数吗?

代码是否有任何错误,或者这不是可变参数的使用方式?

编译器 g++ 11.1.0(使用 clang 也给出相同的错误)

最佳答案

问题是,在最后的递归调用中,rest 对于 printf_vt(s, rest...);; 变为空。并且没有要调用的候选 printf_vt

您可以添加仅使用 const char * 的重载 printf_vt 来匹配上述场景,它也有望终止递归调用。例如

void printf_vt(const char *s)
{
std::cout << s;
}

LIVE

关于c++ - 编译器对模板的无效实例化给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67816795/

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