formatxx icon indicating copy to clipboard operation
formatxx copied to clipboard

sputf

Open edrosten opened this issue 13 years ago • 3 comments

Would you consider adding sputf (or some equivalent) which returned a std::string to the proposal?

I imagine an implementation would be along the lines of:

template <typename CharT, typename... T>
std::string sputf(CharT const *fmt, T const&... t) { ostringstream out; out << putf(fmt, t); return out.str(); };

For my own personal use case, passing a formatted string to a function is more common than writing directly to a string, and I imagine that this is the case for others too.

edrosten avatar Jan 28 '13 11:01 edrosten

On Mon, Jan 28, 2013 at 5:16 AM, Edward Rosten [email protected]:

std::string sputf(CharT const *fmt, T const&... t)

The interface exists in an initial proposal, but latter it's been removed.

The problem is that we have no way to handle an error. Empty returned string, optional<T>, iostates... Any methods have their drawbacks comparing to using an explicit ostringstream.

So the truth is, such an interface is not orthogonal to the concepts used in the streams library. And from the aspect of exceptional-safety, sputf does too much.

Zhihao Yuan, ID lichray The best way to predict the future is to invent it.


4BSD -- http://4bsd.biz/

lichray avatar Jan 29 '13 01:01 lichray

It would be better to define generic

template <typename T>
std::string to_string(const T &value) {
    std::ostringstream ss;
    ss << value;
    return ss.str();
}

and simply write

to_string(puts("format", values...))

That's orthogonal to puts itself and allows things like two-argument form with default, throwing and non-throwing variant and so on. As it's orthogonal, it would make more sense as separate proposal.

jan-hudec avatar Feb 27 '13 22:02 jan-hudec

The to_string overloads in the standard library currently just do not fail. And... ss.exceptions is still not configured (different from boost::format, which has its own .exceptions, std::putf relies on the output stream).

lichray avatar May 09 '13 00:05 lichray