gpt4 book ai didi

c++ - 尝试使用可变参数模板模仿 python 打印函数不起作用

转载 作者:行者123 更新时间:2023-12-04 12:31:45 25 4
gpt4 key购买 nike

我在看书时遇到了可变参数模板,我认为实现 python 风格的 print 函数会很酷。

这是代码。

#include <iostream>
#include <string>

#define None " "

template<typename T, typename... Tail>
void print(T head, Tail... tail, const char* end = "\n")
{
std::cout << head << end;
if constexpr (sizeof...(tail) > 0)
{
print(tail..., end);
}
}

int main()
{
// Error: no instance of function template "print" matches the argument list
print("apple", 0, 0.0f, 'c', true);

// Error: no instance of function template "print" matches the argument list
print("apple", 0, 0.0f, 'c', true, None);
}

这两个函数调用的预期结果:

First:    Second:
apple apple 0 0.0f 'c' 1
0
0.0f
'c'
1

从函数签名中删除 const char* end = "\n" 可以编译代码,但我想要指定最后一个参数的功能来说明是否打印换行符。

这可能吗?

最佳答案

这是可能的,但不是您尝试过的方式。

您可以执行以下操作( 中的一种可能的解决方案):

  • 提供一个枚举(Ending),用于指定打印(即换行、带空格等)。
  • 拆分函数print,其中一个将用于打印一个参数时间,我们将检查打印方式;
  • 另一个print 将用于调用variadicarguments由来电者。这里我们使用 foldexpressions打电话第一个 print 重载。

类似于:( Live Demo )

enum struct Ending {  NewLine = 0, Space };

template<Ending end, typename Type>
void print(const Type& arg) noexcept
{
if constexpr (end == Ending::NewLine) {
std::cout << arg << '\n';
}
else if constexpr (end == Ending::Space) {
std::cout << arg << ' ';
}
}

template <Ending end, typename... Args>
void print(const Args& ... args) noexcept
{
(print<end>(args), ...);
}

现在您可以指定如何结束该行

print<Ending::NewLine>("apple", 0, 0.0f, 'c', true);
print<Ending::Space>("apple", 0, 0.0f, 'c', true);

“你不喜欢重载!?”然后我们可以在立即调用 lambda 函数的帮助下将它放在单个 print 函数中。

( Live Demo )

template <Ending end, typename... Args>
void print(const Args& ... args) noexcept
{
([] (Ending, const auto& arg) noexcept {
if constexpr (end == Ending::NewLine) {
std::cout << arg << '\n';
}
else if constexpr (end == Ending::Space) {
std::cout << arg << ' ';
}
}(end, args), ...);
//^^^^^^^^^^ ^^^^ ---> Invoke the lambda & expand the fold
}

关于c++ - 尝试使用可变参数模板模仿 python 打印函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68560663/

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