如何将 std::ifstream 转换为 std::basic_istream<CharT, Traits>&?

How to convert a std::ifstream to std::basic_istream<CharT, Traits>&?

本文关键字:std lt CharT Traits gt ifstream 转换 basic istream      更新时间:2023-10-16

>我有以下方法:

template<typename CharT, typename Traits, typename Alloc>
auto getline_n(std::basic_istream<CharT, Traits>& in, std::basic_string<CharT, Traits, Alloc>& str, std::streamsize n) -> decltype(in)

此方法的完整版本包含在底部。

我需要能够将 std::ifstream 转换为 std::basic_istream<CharT,>,这样我就可以把它传递给这个方法。

下面是调用代码的外观:

std::ifstream pipe2;
pipe2 = std::ifstream {};
pipe2.open("/<pathToNamedPipe>");
std::basic_istream<char,???> s = pipe2;
std::string line{};
getline_n(s, line, 50);

不太清楚特质以及它们是什么 std::basic_istream? 看???以上。

示例 2(因为人们问我为什么不只传递 pipe2,这是尝试的第一件事 BTW(如下:

std::ifstream pipe2;
pipe2 = std::ifstream {};
pipe2.open("/<pathToNamedPipe>");
std::string line{};
getline_n(pipe2, line, 50);

然后我收到一个 Xcode 编译器错误:

"'std::ifstream' (aka 'basic_ifstream<char>') to 'char **'."

这就是为什么我试图将其转换为 std::basic_istream<char,???>。

这是我想要调用的完整方法:

template<typename CharT, typename Traits, typename Alloc>
auto getline_n(std::basic_istream<CharT, Traits>& in, std::basic_string<CharT, Traits, Alloc>& str, std::streamsize n) -> decltype(in) {
std::ios_base::iostate state = std::ios_base::goodbit;
bool extracted = false;
const typename std::basic_istream<CharT, Traits>::sentry s(in, true);
if(s) {
try {
str.erase();
typename Traits::int_type ch = in.rdbuf()->sgetc();
for(; ; ch = in.rdbuf()->snextc()) {
if(Traits::eq_int_type(ch, Traits::eof())) {
// eof spotted, quit
state |= std::ios_base::eofbit;
break;
}
else if(str.size() == n) {
// maximum number of characters met, quit
extracted = true;
in.rdbuf()->sbumpc();
break;
}
else if(str.max_size() <= str.size()) {
// string too big
state |= std::ios_base::failbit;
break;
}
else {
// character valid
str += Traits::to_char_type(ch);
extracted = true;
}
}
}
catch(...) {
in.setstate(std::ios_base::badbit);
}
}
if(!extracted) {
state |= std::ios_base::failbit;
}
in.setstate(state);
return in;
}

它起源于这个SO帖子:

如何安全地从 std::istream 中读取一行?

这个问题的背景是 std::getline 有一个错误,我正在尝试使用自定义 getline (getline_n( 来解决,如这篇 SO 帖子中所述:

为什么在使用LLVM时,std::ifstream的缓冲会"中断"std::getline?

你没有。

您的std::ifstream已经派生自std::basic_istream<CharT, Traits>.

该函数以这种方式定义,以便您可以根据需要传递对另一种流的 [引用]。

如果程序中其他位置没有错误,则此代码已经有效。