gpt4 book ai didi

c++ - 有没有办法为递归函数部分特化带有参数包的模板?

转载 作者:太空宇宙 更新时间:2023-11-04 15:55:27 25 4
gpt4 key购买 nike

我正在尝试在 C++ 中创建打印功能它接收可变数量的参数并将它们打印在各自的行中,例如:

template<typename Ty, typename... Types>
void println(Ty cur_line, Types... other_lines)
{
std::cout << cur_line << '\n';
println(other_lines);
}
void println() { std::cout << std::flush; }

但是,如果 Ty恰好是 std::vector<std::string> ,我想以不同的方式对待它(因为我想在自己的行上打印 vector 的每个元素)。我研究了部分特化,但在使用参数包这样做时,我似乎找不到太多东西。这是我尝试过的:

template<typename Ty, typename... Types>
void println(Ty cur_line, Types... other_lines)
{
std::cout << cur_line << '\n';
println(other_lines);
}

template<typename... Types>
void println<std::vector<std::string>, Types...>
(std::vector<std::string> cur_line, Types... other_lines)
{
for (const auto& line : cur_line)
{
std::cout << line << '\n';
}
println(other_lines);
}

void println() { std::cout << std::flush; }

但是,我收到 MSVC 错误 C2768:“'println': illegal use of explicit template arguments”。任何建议或解决方案都将受到热烈欢迎!作为引用,我使用的是 Visual Studio 2019 Preview 及其相应的编译器版本。

最佳答案

一个更简单的方法是拥有一个打印函数并重载它:

template < typename T >
void print(const T& line)
{
std::cout << line << '\n';
}

template < typename T >
void print(const std::vector<T>& line)
{
for (const auto& element : line)
{
print(element);
}
}

template<typename Ty, typename... Types>
void println(Ty cur_line, Types... other_lines)
{
print(cur_line);
println(other_lines);
}

void println() { std::cout << std::flush; }

关于c++ - 有没有办法为递归函数部分特化带有参数包的模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59015463/

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