我想创建一个函数来接收 <<
中的任何内容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
其实就是一个函数模板。您可以阅读完整文档 here或 here .它被定义为:
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/