Writing Overloaded Templates
As an example, we’ll build a set of functions that might be useful during debugging. We’ll name our debugging functions debug_rep
, each of which will return a string
representation of a given object. We’ll start by writing the most general version of this function as a template that takes a reference to a const
object:
// print any type we don't otherwise handletemplate <typename T> string debug_rep(const T &t){ ostringstream ret; // see § 8.3 (p. 321) ret << t; // uses T's output operator to print a representation of t return ret.str(); // return a copy of the string to which ret is bound}
This function can be used to generate a string
corresponding to an object of any type that has an output operator.
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.