下面的代码无法工作,并给出了以下编译错误:
严重性代码描述项目文件行抑制状态错误二进制表达式的无效操作数('std::wofstream‘(又名'basic_ofstream >’)
守则是:
template <class T>
void printtofile(std::string filename, int mode, T var, std::wstring msg)
{
wofstream outfile;
if (mode == 0) outfile.open(filename); else outfile.open(filename, ios::out | ios::app);
outfile << msg << L"\n";
outfile << var << L"\n";
outfile.close();
}如果我注释掉下面的一行,没有错误。
outfile << var << L"\n";好吧。奇怪和令人困惑的是,如果我按以下方式添加具有不同参数的函数,则不会出现错误,尽管我没有注释掉上面提到的行:
template <class T>
void printtofile(std::string filename, int mode, T var)
{
wofstream outfile;
if (mode == 0) outfile.open(filename); else outfile.open(filename, ios::out | ios::app);
outfile << var << L"\n";
outfile.close();
}这不是一回事吗?这里发生什么事情?
发布于 2020-04-03 11:51:29
如果outfile << var << L"\n";无法编译,这是因为var的类型没有重载,例如:
std::wofstream& operator<<(std::wofstream&, const T&);例如,如果您试图将一个std::string传递给该函数,这将导致相同的错误。
为了使函数的用户的错误更加清晰,您可以使用SFINAE只实例化受支持类型的模板:
template<class T>
auto printtofile(const std::string& filename, int mode, T var,
const std::wstring& msg)
-> decltype(std::wofstream{} << var, void()) {
//...
}如果您现在尝试将其用于不受支持的类型,则错误将变成如下所示:
error: no matching function for call to
‘printtofile(..., int, <the offending type>, std::wstring&)’发布于 2020-04-03 12:07:49
对于var类型,需要重载var操作符&对于std::string,可以将其简化为C风格的字符串,并绕过错误。
示例:
outfile<<msg.c_str()<<L"\n";
https://stackoverflow.com/questions/61010718
复制相似问题