从临时流中提取字符时 GCC 编译器错误
我正在尝试从流中读取单个字符。使用以下代码,我收到“不明确的重载”编译器错误(GCC 4.3.2、和 4.3.4)。我做错了什么?
#include <iostream>
#include <sstream>
int main()
{
char c;
std::istringstream("a") >> c;
return 0;
}
备注:
- Visual Studio 2008 编译没有错误
- 其他类型(
int
、double
)可以工作 - 如果我首先创建一个变量
std::istringstream iss("a") ;国际空间站>> c
,编译器没有报错
I'm trying to read a single character from a stream. With the following code I get a "ambiguous overload" compiler error (GCC 4.3.2, and 4.3.4). What I'm doing wrong?
#include <iostream>
#include <sstream>
int main()
{
char c;
std::istringstream("a") >> c;
return 0;
}
Remarks:
- Visual Studio 2008 compiles without errors
- Other types (
int
,double
) are working - If I first create a variable
std::istringstream iss("a"); iss >> c
, the compiler gives no error
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字符的提取运算符
>>
是非成员函数模板:由于它通过非
const
引用获取其第一个参数,因此您不能使用临时那里有右值。因此,您的代码无法选择此重载,只能选择各种成员函数重载,其中没有一个与此用法匹配。您的代码在 C++11 中有效,因为还有一个提取运算符将右值引用作为第一个参数。
该编译器的许多非标准扩展之一是允许临时右值绑定到非
const
引用。大多数基本类型的提取运算符都是成员函数,可以在临时上调用右值。
iss
是一个非临时左值,因此它可以绑定到非const
参考。The extraction operator
>>
for characters is a non-member function template:Since this takes its first argument by non-
const
reference, you can't use a temporary rvalue there. Therefore, your code cannot select this overload, only the various member function overloads, none of which match this usage.Your code is valid in C++11, because there is also an extraction operator taking an rvalue reference as the first argument.
One of that compiler's many non-standard extensions is to allow temporary rvalues to be bound to non-
const
references.Most extraction operators for fundamental types are member functions, which can be called on a temporary rvalue.
iss
is a non-temporary lvalue, so it can be bound to a non-const
reference.读取
char
的operator>>
的签名是根据语言规则,临时变量不能绑定到第一个参数,因为临时变量不能绑定到非常量参考。
Visual Studio 2008 允许将其作为 MS 扩展。以后的版本会警告你这是不允许的。
The signature for the
operator>>
reading achar
isAccording to the language rules, a temporary cannot bind to the first parameter as a temporary cannot bind to a non-const reference.
Visual Studio 2008 allows this as an MS extension. Later versions will warn you that it is not allowed.