BDE 4.14.0 Production release
Loading...
Searching...
No Matches
bdlb_nulloutputiterator

Detailed Description

Outline

Purpose

Provide an output iterator type that discards output.

Classes

See also
bdlb_nullinputiterator

Description

This component provides a mechanism, bdlb::NullOutputIterator, that defines an output iterator with the following attributes:

This iterator type is typically used to call functions purely for their side-effects, discarding the normal output. It is also useful for testing whether a template function will compile when presented with a pure output iterator. This component also provides a template bdlb::NullOutputIterator::AssignmentProxy, that is used as the return type of bdlb::NullOutputIterator::operator*. The AssignmentProxy provides an operator= that does nothing, so that the result of the iterator's operator* can be assigned to even if the value type of the bdlb::NullOutputIterator does not provide a default constructor:

class ValueType {
// ... data members ...
public:
ValueType(int value) { ... implementation elided ... }
// ... rest of class definition elided ...
};
ValueType v(42);
// With a non-proxy return type for 'operator*' it would be difficult to
// provide a value for the lefthand side of this expression:
*i = v;
Definition bdlb_nulloutputiterator.h:185

Usage

This section illustrates intended use of this component.

Example 1: Basic Use of bdlb::NullOutputIterator

In the following example we use a bdlb::NullOutputIterator to enable us to call a function to capture its return code, while ignoring the output provided through an iterator.

First, we define a function runningSum that returns output both through an output iterator and through a return status code:

template <class IN_ITER, class OUT_ITER>
typename bsl::iterator_traits<OUT_ITER>::value_type
runningSum(IN_ITER first, IN_ITER last, OUT_ITER output)
{
typename bsl::iterator_traits<OUT_ITER>::value_type total = 0;
while (first != last) {
total += *first++;
*output++ = total;
}
return total;
}

Now, we define a function average that captures the total sum returned by runningSum and uses a bdlb::NullOutputIterator to facilitate calling the function, and ignoring the output it provides through its output iterator parameter:

int average(int values[], int numValues)
{
// ... input validation elided ...
return runningSum(values, values + numValues,
}

Finally, we invoke function average on user array and validate result.

void usageExample()
{
const int myArray[5] = { 3, 4, 5, 7, 11 };
int averageValue = average(myArray, 5);
assert( averageValue == 6 );
}