Channels ▼
RSS

C/C++

An Enhanced ostream_iterator


A Clash of Design Principles?

The constructors of stlsoft::ostream_iterator break an important guideline of consistency between overloads and default arguments. The guideline requires that overloads should behave as if they were implemented as one constructor with a number of default arguments. Additional arguments, which refine the behavior/state requested of the function, are stacked on the end.

Guideline - An overload that provides additional parameters should not change the sequence of parameters with respect to the overridden method.

However, the third overloaded constructor of stlsoft::ostream_iterator specifies its refinement in the middle of the arguments. This is a consequence of applying the Principle of Least Surprise: A user will expect to specify a prefix before a suffix. Doing it the other way would result in client code such as the following:

std::cout << "Header Files:" << std::endl;
std::copy(headers.begin(), headers.end()
    , stlsoft::ostream_iterator<srchseq_t::value_type>(std::cout
                          , "\n","\t"));

This is actually a conflict between levels of discoverability. When viewing the class (template) in isolation, a second overload of (..., suffix, prefix) is probably more discoverable. But when viewed in action, the overload of (..., prefix, suffix) is definitely more discoverable. Given that, I feel that the result is worth transgressing the guideline and have opted for the latter. But it's an equivocal point, to be sure. You may see it differently.

Defining Stream Insertion Operators

You may wonder why this code works as well as it does, specifically why recls::stl:: basic_search_sequence<>::value_type is compatible with ostream_iterator. The reason is that ostream_iterator can work with any type for which a stream insertion operator is defined.

One way we could have implemented this would be as shown in Listing Six. Note that recls::stl::basic_search_sequence<>::value_type is actually the class template recls::stl::basic_search_sequence_value_type<>, whose name is another win for succinctness. (Thankfully, you never need to specify it in client code.)

Listing Six: Stream Insertion Operators

namespace recls::stl
{ 
 std::basic_ostream<char>&
  operator <<(std::basic_ostream<char>&           stm
       , basic_search_sequence_value_type<char, . . .>& v)
 { 
  return stm << v.get_path();
 } 
 std::basic_ostream<wchar_t>&
  operator <<(std::basic_ostream<wchar_t>&           stm
       , basic_search_sequence_value_type<wchar_t, . . .>& v)
 { 
  return stm << v.get_path();
 } 
} // namespace recls::stl

However, there are three problems with this code. First, we've got two functions doing much the same thing. Second, we've had to explicitly choose the traits type that will be supported with basic_search_sequence_value_type. Third, we've assumed that the stream will be derived from std::basic_ostream. A better alternative, which addresses all three problems, is to define the operator as a function template, as shown next. (I separated the return from the insertion, just in case someone wrote an inserter and forgot to provide the expected return type: a mutable [non-const] reference to the stream.)

template<typename S, typename C, typename T>
S& operator <<(S& s, basic_search_sequence_value_type<C, T> const& v)
{ 
 s << v.get_path();
 return s;
} 

This can handle any traits type with which basic_search_sequence may be specialized and works with any stream type that can insert specializations of std::basic_string (the default string type of the recls/STL mapping). And with one additional little flourish—a string access shim, of course—we can make it compatible with any stream type that understands C-style strings.

template<typename S, typename C, typename T>
S& operator <<(S& s, basic_search_sequence_value_type<C, T> const& v)
{ 
 s << stlsoft::c_str_ptr(v.get_path()));
 return s;
} 

Now you can stream to std::cout or even, should you so wish, to an instance of MFC's CArchive!

Implement generic insertion operators.

Summary

We've examined the std::ostream_iterator component and shown how, with relatively little effort, we can enhance its design to support the principles of Composition, Diversity, and Modularity. And, although we've willingly (but advisedly) transgressed an important C++ design principle, the component also supports the Principle of Least Surprise.


Matthew Wilson is a software development consultant for Synesis Software, and creator of the STLSoft libraries. Matthew can be contacted via http://www.synesis.com.au/. This article was excerpted from his book Extended STL, Volume 1 (ISBN 0321305507). Copyright (c) 2007 Addison Wesley Professional. All rights reserved.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video