且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在单个语句中将临时字符串流转换为c_str()

更新时间:2021-11-16 14:57:51

您不能将临时流投射到 std :: ostringstream& 。它格式错误(编译器必须告诉您它是错误的)。不过,可以执行以下操作:

You cannot cast the temporary stream to std::ostringstream&. It is ill-formed (the compiler must tell you that it is wrong). The following can do it, though:

f(static_cast<std::ostringstream&>(
  std::ostringstream().seekp(0) << "Value: " << 5).str().c_str());

那当然是丑陋的。但它显示了它如何工作。 seekp 是一个返回 std :: ostream& 的成员函数。一般情况下,***写上这样的

That of course is ugly. But it shows how it can work. seekp is a member function returning a std::ostream&. Would probably better to write this generally

template<typename T>
struct lval { T t; T &getlval() { return t; } };

f(static_cast<std::ostringstream&>(
  lval<std::ostringstream>().getlval() << "Value: " << 5).str().c_str());

没有任何东西就需要 void * $ c $的原因c>,是因为 operator<< 是成员函数。带有 char const * operator 不是。

The reason that without anything it takes the void*, is because that operator<< is a member-function. The operator<< that takes a char const* is not.