用于计数输入的模板

Templates for cout input

本文关键字:输入 用于      更新时间:2023-10-16

我想创建一个函数,它接受std::cout<<运算符可以处理的任何东西。我有一个坏的例子。

#include <iostream>
template <typename T>
void my_print(const T &t) {
  std::cout << t;
}
int main() {
  my_print("hellon"); // works
  my_print(4); // works
  my_print(std::endl); // compiler error
  return 0;
}

如果我更改为void my_print(T t),它也会失败。编译器错误是

错误:my_print(<未解析的重载函数类型>)的调用没有匹配的函数注:候选人为注:模板类T>void my_print(const T&)

当编译器看到参数t被放入cout时,为什么不能解决它?

是否有任何好的方法来解决这个问题,或者我必须手动提供额外的<<案例,例如void my_print(ostream& (*pf)(ostream&));

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

std::endl实际上是一个函数模板。你可以在这里或这里阅读完整的文档。它被定义为:

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

编辑:你可以使用这个解决方案(我从这里模糊地改编)实现你想要的

#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("hellon"); // works
  my_print(4); // works
  my_print((StandardEndLine)std::endl); // <- NOTE: there is an explicit cast
  return 0;
}