c++ - cout 输入模板

标签 c++ templates stream cout

我想创建一个函数来接收 << 中的任何内容std::cout 的运算符可以处理。我有一个失败的例子。

#include <iostream>

template <typename T>
void my_print(const T &t) {
  std::cout << t;
}

int main() {
  my_print("hello\n"); // works
  my_print(4); // works
  my_print(std::endl); // compiler error
  return 0;
}

如果我改成void my_print(T t)也会失败.编译错误是

error: no matching function for call to 'my_print(<unresolved overloaded function type>)'
note: candidate is
note: template<class T> void my_print(const T&)

为什么编译器在看到参数 t 时无法解析它正在投入 cout

有什么好的方法可以解决这个问题,还是我必须手动提供额外的 <<案例,例如void my_print(ostream& (*pf)(ostream&));

编辑:我知道 endl是一个函数。那么答案是函数类型不被接受为模板吗?就像我不能拥有 [T = ostream& (*)(ostream&)]

最佳答案

std::endl 其实就是一个函数模板。您可以阅读完整文档 herehere .它被定义为:

template< class CharT, class Traits >
std::basic_ostream<charT,traits>& endl( std::basic_ostream<CharT, Traits>& os );

编辑:您可以使用此解决方案(我从 here 中模糊地改编)实现您想要的效果

#include <iostream>

// handles the other types
template <typename T>
void my_print(const T &t) {
  std::cout << t;
}

// alias a few things to make the prototypes readable
typedef std::basic_ostream<char, std::char_traits<char> > CoutType;
typedef CoutType& (*StandardEndLine)(CoutType&);

int main() {
  my_print("hello\n"); // works
  my_print(4); // works
  my_print((StandardEndLine)std::endl); // <- NOTE: there is an explicit cast
  return 0;
}

关于c++ - cout 输入模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16158611/

相关文章:

c++ - 限制可变参数函数模板仅接受一个可变参数类模板的嵌套可变参数类模板的变体?

C++函数不接受具体实现

ffmpeg - 如何在 wowza 中从文件设置传入流?

c# - asp.net mvc生成数据下载文件

c++ - 无法解决 Unresolved external 错误 LNK2019 错误

c++ - 如何在线托管 C 程序

c++ - Magick++ - 减少灰度图像的位深度

templates - 为什么在 play 2 scala 模板中构造的 html 会生成空的 Html 案例类

C++ sync_with_stdio 性能

c++ - 在数组中找到四个元素,其总和等于给定数字 X