gpt4 book ai didi

c++ - 带有 sizeof 的可变参数模板递归...,但编译错误 : no matching function

转载 作者:行者123 更新时间:2023-11-30 00:44:49 27 4
gpt4 key购买 nike

我编写了一个可变参数模板来递归打印所有参数:

#include <iostream>
using std::ostream; using std::istream;
using std::cin; using std::cout; using std::endl;

template <typename T, typename... Args>
ostream &myprint(ostream &os, const T &t, const Args&... rest) {
if (sizeof...(rest)) {
os << t << ", ";
return myprint(os, rest...);
}
else
return os << t;
}

int main(int argc, char *argv[]) {
myprint(cout, "hello");
return 0;
}

但是当我用 g++ -std=c++1y 编译它时,它会提示:

error: no matching function for call to ‘myprint(std::ostream&)’
return myprint(os, rest...);

在函数 myprint 中,我检查了 sizeof...(rest) 的值。当它为 0 时,它不会调用 myprint(os, rest...)。所以不知道为什么会调用myprint(std::ostream&)

而且我也搜索了相关问题,我发现它需要一个基本案例。但为什么我需要一个基本案例,而 sizeof... 不能在可变参数模板中工作?

对于简单的无限递归情况:

template <typename T, typename... Args>
ostream &myprint(ostream &os, const T &t, const Args&... rest) {
os << t << ", "; // print the first argument
return print(os, rest...); // recursive call; print the other arguments
}

同样的错误,上面的代码根本无法编译。

最佳答案

对于if statement statement-truestatement-false 都必须有效,condition 是否满足 true< 的结果false

您可以使用 constexpr if自 C++17 起;当condition 的值为false 时,statement-true 将被丢弃。例如

if constexpr (sizeof...(rest)) {
os << t << ", ";
return myprint(os, rest...);
}
else
return os << t;

如果你不能使用 C++17,你可以为参数数量只有一个的情况添加另一个模板重载,以停止递归,例如

template <typename T>
ostream &myprint(ostream &os, const T &t) {
return os << t;
}

template <typename T, typename... Args>
ostream &myprint(ostream &os, const T &t, const Args&... rest) {
os << t << ", ";
return myprint(os, rest...);
}

LIVE

关于c++ - 带有 sizeof 的可变参数模板递归...,但编译错误 : no matching function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46386877/

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