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

Detailed Description

Provide a trait to enable stream based formatting of a type.

Outline

Purpose

Provide a trait to enable stream based formatting of a type.

Classes

Description

This component provides a trait, EnableStreamedFormatter, that a user can associate with a type, so that type will automatically use the streaming operator (operator<<) when the type is formatted with bsl::format. The EnableStreamedFormatter trait is typically associated with a type using BSLMF_NESTED_TRAIT_DECLARATION (see bslmf_detectnestedtrait ), and indicates that bslfmt::StreamedFormatter (bslfmt_streamedformatter ) should be used to format values of the type.

Be aware that enabling this trait for a type may preclude implementing a more type specific formatter in the future. Users of the type may come to rely on the "string-like" format specification, or the output format, in ways that prevent the type owner for implementing a specific formatter for the type in the future.

For more information read the package documentation .

Usage

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

Enabling Formatting of a Streamable Type

Suppose we own a simple type that supports ostream insert operator<< and want to quickly add bsl::formating capability to it, based on streaming.

First, we introduce a type with a streaming operator but without a formatter that enables bsl::format use:

class NonFormattableType {};
std::ostream& operator<<(std::ostream& os, const NonFormattableType&)
{
return os << "The printout";
}
// The following would not compile:
//
// const NonFormattableType noFormatObj;
// bsl::string s = bsl::format("{}", noFormatObj);
bsl::ostream & operator<<(bsl::ostream &stream, const bdlat_AttributeInfo &attributeInfo)

Then, we enable formatting using the trait (notice the type name changed):

class NowFormattableType {
public:
// TRAITS
BSLMF_NESTED_TRAIT_DECLARATION(NowFormattableType,
};
std::ostream& operator<<(std::ostream& os, const NowFormattableType&)
{
return os << "The printout";
}
#define BSLMF_NESTED_TRAIT_DECLARATION(t_TYPE, t_TRAIT)
Definition bslmf_nestedtraitdeclaration.h:231
Definition bslfmt_enablestreamedformatter.h:141

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

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

Finally, we verify the output is correct:

assert(s == "The printout");