BDE 4.39.x Production Release
Loading...
Searching...
No Matches
bslfmt_streamedformatter

Detailed Description

Provide a formatter that uses the ostream insert operator<<.

Outline

Purpose

Provide a formatter that uses the ostream insert operator<<.

Classes

@SEE ALSO: bslfmt_streamed, bslfmt_enablestreamedformatter

Description

This component provides a base formatter template that may be used to enable bsl::formating of values that have an ostream insert operator<< implemented. The formatting template is also compatible with std::format on platforms where it is provided. Note that this component is not recommended to be used directly but mainly via the bslfmt_streamed component that provides a formattable-wrapper, or by defining the bslfmt_enablestreamedformatter nested trait in the class or template that should have a permanent streamed formatter.

The use case for this component is very narrow, so please read the package documentation before using it and possibly locking yourself into forever supporting an inadequate format string specification.

Usage

In this section we show the intended use of this component.

Enable Formatting of a Streamable Object

Suppose we want to format an object that already supports streaming into an ostream using the insert operator<<.

First, we define the type with a streaming operator, but without a formatter specialization:

class StreamableType {};
std::ostream& operator<<(std::ostream& os, const StreamableType&)
{
return os << "The printout";
}
bsl::ostream & operator<<(bsl::ostream &stream, const bdlat_AttributeInfo &attributeInfo)

Then, we enable formatting of this type using bslfmt::StreamedFormatter as its implementation:

namespace bsl {
template <>
struct formatter<StreamableType, char> :
BloombergLP::bslfmt::StreamedFormatter<StreamableType> {
};
} // close namespace bsl
Definition bdlat_valuetypefunctions.h:939

Next, we create an instance of this type and use bsl::format to format it:

const StreamableType obj;
bsl::string s = bsl::format("{}", obj);
Definition bslstl_string.h:1252

Finally, we verify the output is correct:

assert(s == "The printout");