我想编写一个包装类,根据变量,将或不将日志输出到stdout和/或log.txt.
#include <iostream>
#include <fstream>
using namespace std;
struct A {
bool use_log = 1, use_filelog = 0;
ofstream log_file;
void open() {
use_filelog = 1;
log_file.open("log.txt");
}
};
template <class T> A &operator<<(A &a, T x) {
if (a.use_log) {
std::cout << x;
}
if (a.use_filelog) {
a.log_file << x;
}
return a;
}
int main() {
A a;
a << "Hello, World!" << endl; // <= ERROR
}
当我尝试显示时出现错误endl。我不明白这是什么问题。
这个类可以用其他方式实现吗?
这是输出画布的开头gcc:
4.cpp: In function ‘int main()’:
4.cpp:26:24: error: no match for ‘operator<<’ (operand types are ‘A’ and ‘<unresolved overloaded function type>’)
a << "Hello, World!" << endl;
^
4.cpp:14:23: note: candidate: template<class T> A& operator<<(A&, T)
template <class T> A &operator<<(A &a, T x) {
^
4.cpp:14:23: note: template argument deduction/substitution failed:
4.cpp:26:27: note: couldn't deduce template parameter ‘T’
a << "Hello, World!" << endl;
^
In file included from /usr/include/c++/5/iostream:39:0,
from 4.cpp:1:
/usr/include/c++/5/ostream:628:5: note: candidate: template<class _CharT, class _Traits, class _Tp> std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&)
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
但是来自clang:
prog.cpp:26:27: error: reference to overloaded function could not be resolved; did you mean to call it?
a << "Hello, World!" << endl;
^~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/ostream:590:5: note: possible target for call
endl(basic_ostream<_CharT, _Traits>& __os)
^
prog.cpp:14:23: note: candidate template ignored: couldn't infer template argument 'T'
template <class T> A &operator<<(A &a, T x) {
std::endl没有特定的类型,因为它本身就是一个函数模板。因此,表格的记录是不明确的,不可能从中导出模板参数。编译器告诉你什么。要消除歧义,您必须明确指定至少一个模板的参数。
例如,如果您显式指定模板参数
std::endl然后你的类型被
T成功推断出来,你的操作员将按预期工作。但是为了不在现实中这样变态,可以类比标准流,再创建一个专门为输出设计的输出语句
std::endl同时,这个算子的实现,在模板参数
std::endl已经固定后,不能显式写出来,而是委托给你的模板算子(这里需要注意不要安排递归)为了支持其余的操纵器,您必须从链接中实施组 10-12 的其余运算符。