【问题标题】:How to print multiple variables of different type to console in C++如何在 C++ 中将多个不同类型的变量打印到控制台
【发布时间】:2019-11-08 05:38:27
【问题描述】:

我是 C++ 初学者,经过几分钟的编码,我厌倦了手动输入 "std:cout

template < typename T > void printL(T t){
    std::cout << t << std::endl;
}

template < typename T, typename ...F > void printL(T t, F ...f) {

    std::cout << t << printL(f...) << std::flush;
}

int main() {
    printL("the quick brown fox jumps over the lazy dog ", "dog");

    return 0;

它应该输出这个:

the quick brown fox jumps over the lazy dog dog

代码应该接受一些未知的参数,并且类型也是未知的。它应该将它们打印在一行中并以新行结束打印功能。

【问题讨论】:

  • 如果您是真正的初学者,您可能还不应该使用模板。这不是简单的学习方法。但无论如何......
  • 我的意思是我以前用过其他语言而不是 C++

标签: c++ templates variadic


【解决方案1】:

使用 C++17 fold expressions,更简单

template <typename... T> void printL(T... t) {
    (std::cout << ... << t) << std::endl;
}

【讨论】:

  • 您需要像这样添加括号:(std::cout &lt;&lt; ... &lt;&lt; t) &lt;&lt; std::endl。它们是折叠表达式的一部分。
  • 已经投票了,但我也试图让它工作,但无法弄清楚语法。我正在尝试(&lt;&lt; ...t)
【解决方案2】:

您的函数被定义为返回void,因此您的代码将无法运行。 相反,只需打印第一个参数,然后进行递归调用以打印其余参数。

std::cout << t;
printL(f...);

您的终止实现使用std::endl,并且已经刷新。

【讨论】:

  • 非常感谢,我发现 C++ 比我预期的要难
  • @Rios 好吧,模板有时甚至会绊倒一些高级用户。所以你所学的并不是 C++ 的简单部分。
  • @Chipster 是的,没错,我掉进了兔子洞,我不想放弃或寻求帮助,但是哦,哈哈
猜你喜欢
  • 2018-11-24
  • 1970-01-01
  • 2016-05-01
  • 2014-08-22
  • 2018-05-12
  • 1970-01-01
  • 2013-02-10
  • 2011-01-11
  • 1970-01-01
相关资源
最近更新 更多