用于计数输入的模板
Templates for cout input
我想创建一个函数,它接受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;
}
相关文章:
- LLVM | codegen 用于带有命令行选项的程序输入功能
- 用于获取枚举值的用户输入
- 一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 在一个子程序中输入的变量用于C++中的另一个子程序
- 为什么给定的代码不适用于所有测试用例?为什么当输入为 7786 时它不起作用?
- 为什么用于获取有关名称的输入的语法不起作用?
- 为什么我的递归最长递增子序列函数不适用于大输入?
- 用于了解输入和输出流缓冲区实际工作方式的程序
- 在此代码中,它不接受 i=0 的输入.它直接用于 i=1
- Tensorflow C++ 用于动态输入形状的 API
- 代码似乎不适用于较大的输入,但适用于较小的输入
- 流输入运算符导致分段错误与 clang 但适用于 gcc
- C++ 代码中的质因数并不适用于所有输入
- 用于使用可选输入文件运行 C++ 的 VIM 映射
- 输入/矢量数组不适用于发送输入
- C 两个线程一个用于输入,一个用于输出
- 切换输入用于排序算法
- C++ 将用户输入数据用于多个函数
- 如何使用 arc4 输入用于加密的字符串