[英]double to string with ostringstream syntax
I'd like to understand why writing this 我想了解为什么写这个
static_cast<std::ostringstream*>( &(std::ostringstream() << speed.x) )->str();
makes a string, but not this 做一个字符串,但不是这个
(std::ostringstream() << speed.x).str();?
in fact the latter doesn't even compile... 实际上,后者甚至无法编译...
I find this static_cast<foo*>&foo
to be quite weird. 我发现这个
static_cast<foo*>&foo
很奇怪。
can you give me good examples in which case it's good practice to do so? 在这种情况下,您能给我很好的例子吗?
The the expression std::ostringstream() << speed.x
actually invokes the operator<<(double)
on the underlying base class std::ostream
interface. 表达式
std::ostringstream() << speed.x
实际上在基础基类std::ostream
接口上调用operator<<(double)
。
The return type of std::ostream::operator<<(double)
is std::ostream&
which means you're trying to invoke the member function std::ostream::str()
which of course does not exist. std::ostream::operator<<(double)
的返回类型为std::ostream&
,这意味着您试图调用成员函数std::ostream::str()
当然不存在。 That method is on the derived class. 该方法在派生类上。
This is why the static_cast
is necessary in this use case. 这就是为什么在此用例中需要
static_cast
原因。
You could also write: 您还可以编写:
static_cast<std::ostringstream&>(std::ostringstream() << speed.x).str();
or since c++11 或自c ++ 11起
std::to_string(speed.x);
or in previous versions, you could write your own, less cryptic function which will do the same thing in a more maintainable way with no overhead. 或在以前的版本中,您可以编写自己的,较少隐秘的函数,该函数将以更可维护的方式完成相同的任务而没有任何开销。
std::string to_string(double x)
{
std::ostringstream ss;
ss << x;
return ss.str();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.