1

下面的代码不起作用并给出以下编译错误:

严重性代码描述项目文件行抑制状态错误二进制表达式的操作数无效('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();
}

这不是一回事吗?这里发生了什么?

4

2 回答 2

1

您需要为&<<类型重载运算符,因为您可以将其减少为 C 样式字符串并绕过错误。varstd::string

例子:

outfile<<msg.c_str()<<L"\n";

于 2020-04-03T12:07:49.063 回答
1

如果outfile << var << L"\n";编译失败,那是因为它的var类型没有重载,例如:

std::wofstream& operator<<(std::wofstream&, const T&);

例如,如果您尝试将 a 传递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-03T11:51:29.873 回答