Streams and Files - TableFormatter Template (Page 4 of 4 )
As with all other character-based classes in the standard library, manipulators work on streams that use narrow or wide characters. Therefore, you can use them with templates to write formatting utilities that operate on streams of any kind of character. Example 10-2 presents the class template TableFormatter, which formats data into equal-width columns and writes it to a stream.
template<typename valT> void writeTableRow(const vector<valT>& v, int width); //...
private: basic_ostream<T>& out_; };
template<typename T> // refers to class template param list template<typename valT> // refers to mem fn template param list void TableFormatter<T>::writeTableRow(const std::vector<valT>& v, int width) {
ios_base::fmtflags flags = out_.flags();
out_.flush(); out_ << setprecision(2) << fixed; // Set the precision, in case // this is floating-point data for (vector<valT>::const_iterator p = v.begin(); p != v.end(); ++p) out_ << setw(width) << left << *p; // Set the width, justify, // and write the element out_ << endl; // Flush out_.setf(flags); // Set the flags back to normal }
Please check back next week for the continuation of this article.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.