<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/rss2full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/itemcontent.css" type="text/css" media="screen"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">

<channel>
	<title>Learn C++</title>
	
	<link>http://www.learncpp.com</link>
	<description />
	<pubDate>Tue, 18 Nov 2008 04:10:56 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/LearnCpp" type="application/rss+xml" /><item>
		<title>15.6 — Exception dangers and downsides</title>
		<link>http://www.learncpp.com/cpp-tutorial/156-exception-dangers-and-downsides/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/156-exception-dangers-and-downsides/#comments</comments>
		<pubDate>Sun, 26 Oct 2008 20:27:27 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
		
		<category><![CDATA[C++ Tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=217</guid>
		<description><![CDATA[As with almost everything that has benefits, there are some potential downsides to exceptions as well.  This article is not meant to be comprehensive, but just to point out some of the major issues that should be considered when using exceptions (or deciding whether to use them).
&#1058;&#1102;&#1084;&#1077;&#1085;&#1100; &#1083;&#1072;&#1085;&#1076;&#1096;&#1072;&#1092;&#1090;Cleaning up resources
One of the biggest problems [...]]]></description>
			<content:encoded><![CDATA[<p>As with almost everything that has benefits, there are some potential downsides to exceptions as well.  This article is not meant to be comprehensive, but just to point out some of the major issues that should be considered when using exceptions (or deciding whether to use them).</p>
<p><strong><noscript><a href="http://www.sibresource.ru/">&#1058;&#1102;&#1084;&#1077;&#1085;&#1100; &#1083;&#1072;&#1085;&#1076;&#1096;&#1072;&#1092;&#1090;</a></noscript>Cleaning up resources</strong></p>
<p>One of the biggest problems that new programmers run into when using exceptions is the issue of cleaning up resources when an exception occurs.  Consider the following example:</p>
<pre name="code" class="cpp">

try
{
    OpenFile(strFilename);
    WriteFile(strFilename, strData);
    CloseFile(strFilename);
}
catch (FileException &amp;cException)
{
    cerr &lt;&lt; &quot;Failed to write to file: &quot; &lt;&lt; cException.what() &lt;&lt; endl;
}
</pre>
<p>What happens if WriteFile() fails and throws a FileException?  At this point, we&#8217;ve already opened the file, and now control flow jumps to the FileException handler, which prints an error and exits.  Note that the file was never closed!  This example should be rewritten as follows:</p>
<pre name="code" class="cpp">

try
{
    OpenFile(strFilename);
    WriteFile(strFilename, strData);
    CloseFile(strFilename);
}
catch (FileException &amp;cException)
{
    // Make sure file is closed
    CloseFile(strFilename);
    // Then write error
    cerr &lt;&lt; &quot;Failed to write to file: &quot; &lt;&lt; cException.what() &lt;&lt; endl;
}
</pre>
<p>This kind of error often crops up in another form when dealing with dynamically allocated memory:</p>
<pre name="code" class="cpp">

try
{
    Person *pJohn = new Person(&quot;John&quot;, 18, E_MALE);
    ProcessPerson(pJohn);
    delete pJohn;
}
catch (PersonException &amp;cException)
{
    cerr &lt;&lt; &quot;Failed to process person: &quot; &lt;&lt; cException.what() &lt;&lt; endl;
}
</pre>
<p>If ProcessPerson() throws an exception, control flow jumps to the catch handler.  As a result, pJohn is never deallocated!  This example is a little more tricky than the previous one &#8212; because pJohn is local to the try block, it goes out of scope when the try block exits.  That means the exception handler can not access pJohn at all (its been destroyed already), so there&#8217;s no way for it to deallocate the memory.</p>
<p>However, there are two relatively easy ways to fix this.  First, declare pJohn outside of the try block so it does not go out of scope when the try block exits:</p>
<pre name="code" class="cpp">

Person *pJohn = NULL;
try
{
    pJohn = new Person(&quot;John&quot;, 18, E_MALE);
    ProcessPerson(pJohn );
    delete pJohn;
}
catch (PersonException &amp;cException)
{
    delete pJohn;
    cerr &lt;&lt; &quot;Failed to process person: &quot; &lt;&lt; cException.what() &lt;&lt; endl;
}
</pre>
<p>Because pJohn is declared outside the try block, it is accessible both within the try block and the catch handlers.  This means the catch handler can do cleanup properly.</p>
<p>The second way is to use a local variable of a class that knows how to cleanup itself when it goes out of scope.  The standard library provides a class called std::auto_ptr that can be used for this purpose.  <strong>std::auto_ptr</strong> is a template class that holds a pointer, and deallocates it when it goes out of scope.</p>
<pre name="code" class="cpp">

#include &lt;memory&gt; // for std::auto_ptr
try
{
    pJohn = new Person(&quot;John&quot;, 18, E_MALE);
    auto_ptr&lt;Person&gt; pxJohn(pJohn); // pxJohn now owns pJohn

    ProcessPerson(pJohn);

    // when pxJohn goes out of scope, it will delete pJohn
}
catch (PersonException &amp;cException)
{
    cerr &lt;&lt; &quot;Failed to process person: &quot; &lt;&lt; cException.what() &lt;&lt; endl;
}
</pre>
<p>Note that std::auto_ptr should not be set to point to arrays.  This is because it uses the delete operator to clean up, not the delete[] operator.  In fact, there is no array version of std::auto_ptr!  It turns out, there isn&#8217;t really a need for one.  In the standard library, if you want to do dynamically allocated arrays, you&#8217;re supposed to use the std::vector class, which will deallocate itself when it goes out of scope.</p>
<p><strong>Exceptions and destructors</strong></p>
<p>Unlike constructors, where throwing exceptions can be a useful way to indicate that object creation succeeded, exceptions should <em>not</em> be thrown in destructors.</p>
<p>The problem occurs when an exception is thrown from a destructor during the stack unwinding process.  If that happens, the compiler is put in a situation where it doesn&#8217;t know whether to continue the stack unwinding process or handle the new exception.  The end result is that your program will be terminated immediately.</p>
<p>Consequently, the best course of action is just to abstain from using exceptions in destructors altogether.  Write a message to a log file instead.</p>
<p><strong>Performance concerns</strong></p>
<p>Exceptions do come with a small performance price to pay.  They increase the size of your executable, and they will also cause it to run slower due to the additional checking that has to be performed.  However, the main performance penalty for exceptions happens when an exception is actually thrown.  In this case, the stack must be unwound and an appropriate exception handler found, which is a relatively an expensive operation.  Consequently, exception handling should only be used for truly exceptional cases and catastrophic errors.</p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle><font style="position: absolute;overflow: hidden;height: 0;width: 0"><a href="http://sikongroup.com/rentacar/index.htm">rent a car bulgaria</a></font> </a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter15" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/up.png" align=middle> Index</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/155-exceptions-classes-and-inheritance/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 15.5 &#8212; Exceptions, classes, and inheritance</a>
</td>
</tr>
</table>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~f/LearnCpp?a=qrLKM"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=qrLKM" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=t9zEM"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=t9zEM" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=CW4Om"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=CW4Om" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=hu7Mm"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=hu7Mm" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/156-exception-dangers-and-downsides/feed/</wfw:commentRss>
		</item>
		<item>
		<title>15.5 — Exceptions, classes, and inheritance</title>
		<link>http://www.learncpp.com/cpp-tutorial/155-exceptions-classes-and-inheritance/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/155-exceptions-classes-and-inheritance/#comments</comments>
		<pubDate>Sun, 26 Oct 2008 17:52:43 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
		
		<category><![CDATA[C++ Tutorial]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[classes]]></category>

		<category><![CDATA[exceptions]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[std::exception]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=216</guid>
		<description><![CDATA[Exceptions and member functions
Up to this point in the tutorial, you&#8217;ve only seen exceptions used in non-member functions.  However, exceptions are equally useful in member functions, and even moreso in overloaded operators.  Consider the following overloaded [] operator as part of a simple integer array class:


int IntArray::operator[](const int nIndex)
{
    return [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Exceptions and member functions</strong></p>
<p>Up to this point in the tutorial, you&#8217;ve only seen exceptions used in non-member functions.  However, exceptions are equally useful in member functions, and even moreso in overloaded operators.  Consider the following overloaded [] operator as part of a simple integer array class:</p>
<pre name="code" class="cpp">

int IntArray::operator[](const int nIndex)
{
    return m_nData[nIndex];
}
</pre>
<p>Although this function will work great as long as nIndex is a valid array index, this function is sorely lacking in some good error checking.  We could add an assert statement to ensure the index is valid:</p>
<pre name="code" class="cpp">

int IntArray::operator[](const int nIndex)
{
    assert (nIndex &gt;= 0 &amp;&amp; nIndex &lt; GetLength());
    return m_nData[nIndex];
}
</pre>
<p>Now if the user passes in an invalid index, the program will cause an assertion error.  While this is useful to indicate to the user that something went wrong, sometimes the better course of action is to fail silently and let the caller know something went wrong so they can deal with it as appropriate.</p>
<p>Unfortunately, because overloaded operators have specific requirements as to the number and type of parameter(s) they can take and return, there is no flexibility for passing back error codes or boolean values to the caller.  However, since exceptions do not change the signature of a function, they can be put to great use here.  Here&#8217;s an example:</p>
<pre name="code" class="cpp">

int IntArray::operator[](const int nIndex)
{
    if (nIndex &lt; 0 || nIndex &gt;= GetLength())
        throw nIndex;

    return m_nData[nIndex];
}
</pre>
<p>Now, if the user passes in an invalid exception, operator[] will throw an int exception.</p>
<p><strong>When constructors fail</strong></p>
<p>Constructors are another area of classes in which exceptions can be very useful.  If a constructor fails, simply throw an exception to indicate the object failed to create.  The object&#8217;s construction is aborted and its destructor is never executed.</p>
<p><strong>Exception classes</strong></p>
<p>One of the major problem with using basic data types (such as int) as exception types is that they are inherently vague.  An even bigger problem is disambiguation of what an exception means when there are multiple statements or function calls within a try block.</p>
<pre name="code" class="cpp">

try
{
    int *nValue = new int(anArray[nIndex1] + anArray[nIndex2]);
}
catch (int nValue)
{
    // What are we catching here?
}
</pre>
<p>In this example, if we were to catch an int exception, what does that really tell us?  Was one of the array indexes out of bounds?  Did operator+ cause integer overflow?  Did operator new fail because it ran out of memory?  Unfortunately, in this case, there&#8217;s just no easy way to disambiguate.  While we can throw char* exceptions to solve the problem of identifying WHAT went wrong, this still does not provide us the ability to handle exceptions from various sources differently.</p>
<p>One way to solve this problem is to use exception classes.  An <strong>exception class</strong> is just a normal class that is designed specifically to be thrown as an exception.  Let&#8217;s design a simple exception class to be used with our IntArray class:</p>
<pre name="code" class="cpp">

class ArrayException
{
private:
    std::string m_strError;

    ArrayException() {}; // not meant to be called
public:
    ArrayException(std::string strError)
        : m_strError(strError)
    {
    }

    std::string GetError() { return m_strError; }
}
</pre>
<p>Here&#8217;s our overloaded operator[] throwing this class:</p>
<pre name="code" class="cpp">

int IntArray::operator[](const int nIndex)
{
    if (nIndex &lt; 0 || nIndex &gt;= GetLength())
        throw ArrayException(&quot;Invalid index&quot;);

    return m_nData[nIndex];
}
</pre>
<p>And a sample usage of this class:</p>
<pre name="code" class="cpp">

try
{
    int nValue = anArray[5];
}
catch (ArrayException &amp;cException)
{
    cerr &lt;&lt; &quot;An array exception occurred (&quot; &lt;&lt; cException.GetError() &lt;&lt; &quot;)&quot; &lt;&lt; endl;
}
</pre>
<p>Using such a class, we can have the exception return a description of the problem that occurred, which provides context for what went wrong.  And since ArrayException is it&#8217;s own unique type, we can specifically catch exceptions thrown by the array class and treat them differently from other exceptions if we wish.</p>
<p>Note that exception handlers should catch class exception objects by reference instead of by value.  This prevents the compiler from make a copy of the exception, which can be expensive when the exception is a class object.  Catching exceptions by pointer should generally be avoided unless you have a specific reason to do so.</p>
<p><strong>std::exception</strong></p>
<p>The C++ standard library comes with an exception class that is used by many of the other standard library classes.  The class is almost identical to the ArrayException class above, except the GetError() function is named what():</p>
<pre name="code" class="cpp">

try
{
    // do some stuff with the standard library here
}
catch (std::exception &amp;cException)
{
    cerr &lt;&lt; &quot;Standard exception: &quot; &lt;&lt; cException.what() &lt;&lt; endl;
}
</pre>
<p>We&#8217;ll talk more about std::exception in a moment.</p>
<p><strong>Exceptions and inheritance</strong></p>
<p>Since it&#8217;s possible to throw classes as exceptions, and classes can be derived from other classes, we need to consider what happens when we use inherited classes as exceptions.  As it turns out, exception handlers will not only match classes of a specific type, they&#8217;ll also match classes derived from that specific type as well!  Consider the following example:</p>
<pre name="code" class="cpp">

class Base
{
public:
    Base() {}
};

class Derived: public Base
{
public:
    Derived() {}
};

int main()
{
    try
    {
        throw Derived();
    }
    catch (Base &amp;cBase)
    {
        cerr &lt;&lt; &quot;caught Base&quot;;
    }
    catch (Derived &amp;cDerived)
    {
        cerr &lt;&lt; &quot;caught Derived&quot;;
    }

    return 0;
}	
</pre>
<p>In the above example we throw an exception of type Derived.  However, the output of this program is:</p>
<pre>
caught Base
</pre>
<p>What happened?</p>
<p>First, as mentioned above, derived classes will be caught by handlers for the base type.  Because Derived is derived from Base, Derived is-a Base (they have an is-a relationship).  Second, when C++ is attempting to find a handler for a raised exception, it does so sequentially.  Consequently, the first thing C++ does is check whether the exception handler for Base matches the Derived exception.  Because Derived is-a Base, the answer is yes, and it executes the catch block for type Base!  The catch block for Derived is never even tested in this case.</p>
<p>In order to make this example work as expected, we need to flip the order of the catch blocks:</p>
<pre name="code" class="cpp">

class Base
{
public:
    Base() {}
};

class Derived: public Base
{
public:
    Derived() {}
};

int main()
{
    try
    {
        throw Derived();
    }
    catch (Derived &amp;cDerived)
    {
        cerr &lt;&lt; &quot;caught Derived&quot;;
    }
    catch (Base &amp;cBase)
    {
        cerr &lt;&lt; &quot;caught Base&quot;;
    }

    return 0;
}	
</pre>
<p>This way, the Derived handler will get first shot at catching objects of type Derived (before the handler for Base can).  Objects of type Base will not match the Derived handler (Derived is-a Base, but Base is not a Derived), and thus will &#8220;fall through&#8221; to the Base handler.</p>
<p><em>Rule: Handlers for derived exception classes should be listed before those for base classes.</em></p>
<p>The ability to use a handler to catch exceptions of derived types using a handler for the base class turns out to be exceedingly useful.</p>
<p>Let&#8217;s take a look at this using std::exception.  There are many classes derived from std::exception, such as std::bad_alloc, std::bad_cast, std::runtime_error, and others.  When the standard library has an error, it can throw a derived exception correlating to the appropriate specific problem it has encountered.</p>
<p>Most of the time, we probably won&#8217;t care whether the problem was a bad allocation, a bad cast, or something else.  We just care that we got an exception from the standard library.  In this case, we just set up an exception handler to catch std::exception, and we&#8217;ll end up catching std::exception and all of the derived exceptions together in one place.  Easy!</p>
<pre name="code" class="cpp">

try
{
     // code using standard library goes here
}
// This handler will catch std::exception and all the derived exceptions too
catch (std::exception &amp;cException)
{
    cerr &lt;&lt; &quot;Standard exception: &quot; &lt;&lt; cException.what() &lt;&lt; endl;
}
</pre>
<p>However, sometimes we&#8217;ll want to handle a specific type of exception differently.  In this case, we can add a handler for that specific type, and let all the others &#8220;fall through&#8221; to the base handler.  Consider:</p>
<pre name="code" class="cpp">

try
{
     // code using standard library goes here
}
// This handler will catch std::bad_alloc (and any exceptions derived from it) here
catch (std::bad_alloc &amp;cException)
{
    cerr &lt;&lt; &quot;You ran out of memory!&quot; &lt;&lt; endl;
}
// This handler will catch std::exception (and any exception derived from it) that fall
// through here
catch (std::exception &amp;cException)
{
    cerr &lt;&lt; &quot;Standard exception: &quot; &lt;&lt; cException.what() &lt;&lt; endl;
}
</pre>
<p>In this example, exceptions of type std::bad_alloc will be caught by the first handler and handled there.  Exceptions of type std::exception and all of the other derived classes will be caught by the second handler.</p>
<p>Such inheritance hierarchies allow us to use specific handlers to target specific derived exception classes, or to use base class handlers to catch the whole hierarchy of exceptions.  This allows us a fine degree of control over what kind of exceptions we want to handle while ensuring we don&#8217;t have to do too much work to catch &#8220;everything else&#8221; in a hierarchy.</p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/156-exception-dangers-and-downsides/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle> 15.6 &#8212; Exception dangers and downsides </a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter15" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/up.png" align=middle> Index</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/154-uncaught-exceptions-catch-all-handlers-and-exception-specifiers/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 15.4 &#8212; Uncaught exceptions, catch-all handlers, and exception specifiers</a>
</td>
</tr>
</table>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~f/LearnCpp?a=IGIrM"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=IGIrM" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=Q9LtM"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=Q9LtM" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=q718m"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=q718m" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=K4Nwm"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=K4Nwm" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/155-exceptions-classes-and-inheritance/feed/</wfw:commentRss>
		</item>
		<item>
		<title>15.4 — Uncaught exceptions, catch-all handlers, and exception specifiers</title>
		<link>http://www.learncpp.com/cpp-tutorial/154-uncaught-exceptions-catch-all-handlers-and-exception-specifiers/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/154-uncaught-exceptions-catch-all-handlers-and-exception-specifiers/#comments</comments>
		<pubDate>Sat, 25 Oct 2008 20:07:37 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
		
		<category><![CDATA[C++ Tutorial]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[catch-all handler]]></category>

		<category><![CDATA[exception specifiers]]></category>

		<category><![CDATA[exceptions]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=215</guid>
		<description><![CDATA[By now, you should have a reasonable idea of how exceptions work.  In this lesson, we&#8217;ll cover a few more interesting exception cases.
Uncaught exceptions
In the past few examples, there are quite a few cases where a function assumes its caller (or another function somewhere up the call stack) will handle the exception.  In [...]]]></description>
			<content:encoded><![CDATA[<p>By now, you should have a reasonable idea of how exceptions work.  In this lesson, we&#8217;ll cover a few more interesting exception cases.</p>
<p><strong>Uncaught exceptions</strong></p>
<p>In the past few examples, there are quite a few cases where a function assumes its caller (or another function somewhere up the call stack) will handle the exception.  In the following example, MySqrt() assumes someone will handle the exception that it throws &#8212; but what happens if nobody actually does?</p>
<p>Here&#8217;s our square root program again, minus the try block in main():</p>
<pre name="code" class="cpp">

#include &quot;math.h&quot; // for sqrt() function
using namespace std;

// A modular square root function
double MySqrt(double dX)
{
    // If the user entered a negative number, this is an error condition
    if (dX &lt; 0.0)
        throw &quot;Can not take sqrt of negative number&quot;; // throw exception of type char*

    return sqrt(dX);
}

int main()
{
    cout &lt;&lt; &quot;Enter a number: &quot;;
    double dX;
    cin &gt;&gt; dX;

    // Look ma, no exception handler!
    cout &lt;&lt; &quot;The sqrt of &quot; &lt;&lt; dX &lt;&lt; &quot; is &quot; &lt;&lt; MySqrt(dX) &lt;&lt; endl;
}
</pre>
<p>Now, let&#8217;s say the user enters -4, and MySqrt(-4) raises an exception.  MySqrt() doesn&#8217;t handle the exception, so the program stack unwinds and control returns to main().  But there&#8217;s no exception handler here either, so main() terminates.  At this point, we just terminated our application!</p>
<p>When main() terminates with an unhandled exception, the operating system will generally notify you that an unhandled exception error has occurred.  How it does this depends on the operating system, but possibilities include printing an error message, popping up an error dialog, or simply crashing.  Some OS&#8217;s are less graceful than others.  Generally this is something you want to avoid altogether!</p>
<p><strong>Catch-all handlers</strong></p>
<p>And now we find ourselves in a condundrum: functions can potentially throw exceptions of any data type, and if an exception is not caught, it will propagate to the top of your program and cause it to terminate.  Since it&#8217;s possible to call functions without knowing how they are even implemented, how can we possibly prevent this from happening?</p>
<p>Fortunately, C++ provides us with a mechanism to catch all types of exceptions.  This is known as a <strong>catch-all handler</strong>.  A catch-all handler works just like a normal catch block, except that instead of using a specific type to catch, it uses the ellipses operator (&#8230;) as the type to catch.  If you recall from lesson 7.14 on <a href="http://www.learncpp.com/cpp-tutorial/714-ellipses-and-why-to-avoid-them/">ellipses and why to avoid them</a>, ellipses were previously used to pass arguments of any type to a function.  In this context, they represent exceptions of any data type.  Here&#8217;s an simple example:</p>
<pre name="code" class="cpp">

try
{
    throw 5; // throw an int exception
}
catch (double dX)
{
    cout &lt;&lt; &quot;We caught an exception of type double: &quot; &lt;&lt; dX &lt;&lt; endl;
}
catch (...) // catch-all handler
{
    cout &lt;&lt; &quot;We caught an exception of an undetermined type&quot; &lt;&lt; endl;
}
</pre>
<p>Because there is no specific exception handler for type int, the catch-all handler catches this exception.  This example produces the following result:</p>
<pre>
We caught an exception of an undetermined type
</pre>
<p>The catch-all handler should be placed last in the catch block chain.  This is to ensure that exceptions can be caught by exception handlers tailored to specific data types if those handlers exist.  Visual Studio enforces this constraint &#8212; I am unsure if other compilers do.</p>
<p>Often, the catch-all handler block is left empty:</p>
<pre name="code" class="cpp">

catch(...) {} // ignore any unanticipated exceptions
</pre>
<p>This will catch any unanticipated exceptions and prevent them from stack unwinding to the top of your program, but does no specific error handling.</p>
<p><strong>Using the catch-all handler to wrap main()</strong></p>
<p>One interesting use for the catch-all handler is to wrap the contents of main():</p>
<pre name="code" class="cpp">

int main()
{

    try
    {
        RunGame();
    }
    catch(...)
    {
        cerr &lt;&lt; &quot;Abnormal termination&quot; &lt;&lt; endl;
    }

    SaveState(); // Save user&#039;s game
    return 1;
}
</pre>
<p>In this case, if RunGame() or any of the functions it calls throws an exception that is not caught, that exception will unwind up the stack and eventually get caught by this catch-all handler.  This will prevent main() from terminating, and gives us a chance to print an error of our choosing and then save the user&#8217;s state before exiting.  This can be useful to catch and handle problems that may be unanticipated.</p>
<p><strong>Exception specifiers</strong></p>
<p>This subsection should be considered optional reading because exception specifiers are rarely used in practice, are not well supported by compilers, and Bjarne Stroustrup (the creator of C++) considers them a failed experiment.</p>
<p><strong>Exception specifiers</strong> are a mechanism that allows us to use a function declaration to specify whether a function may or will not throw exceptions.  This can be useful in determining whether a function call needs to be put inside a try block or not.</p>
<p>There are three types of exception specifiers, all of which use what is called the <strong>throw (&#8230;)</strong> syntax.</p>
<p>First, we can use an empty throw statement to denote that a function does not throw any exceptions outside of itself:</p>
<pre name="code" class="cpp">

int DoSomething() throw(); // does not throw exceptions
</pre>
<p>Note that DoSomething() can still use exceptions as long as they are handled internally.  Any function that is declared with throw() is supposed to cause the program to terminate immediately if it does try to throw an exception outside of itself, but implementation is spotty.</p>
<p>Second, we can use a specific throw statement to denote that a function may throw a particular type of exception:</p>
<pre name="code" class="cpp">

int DoSomething() throw(double); // may throw a double
</pre>
<p>Finally, we can use a catch-all throw statement to denote that a function may throw an unspecified type of exception:</p>
<pre name="code" class="cpp">

int DoSomething() throw(...); // may throw anything
</pre>
<p>Due to the incomplete compiler implementation, the fact that exception specifiers are more like statements of intent than guarantees, some incompatibility with template functions, and the fact that most C++ programmers are unaware of their existence, I recommend you do not bother using exception specifiers.</p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/155-exceptions-classes-and-inheritance/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle> 15.5 &#8212; Exceptions, classes, and inheritance</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter15" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/up.png" align=middle> Index</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/153-exceptions-functions-and-stack-unwinding/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 15.3 &#8212; Exceptions, functions, and stack unwinding</a>
</td>
</tr>
</table>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~f/LearnCpp?a=oscDM"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=oscDM" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=qD5vM"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=qD5vM" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=mmfHm"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=mmfHm" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=A4W2m"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=A4W2m" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/154-uncaught-exceptions-catch-all-handlers-and-exception-specifiers/feed/</wfw:commentRss>
		</item>
		<item>
		<title>15.3 — Exceptions, functions, and stack unwinding</title>
		<link>http://www.learncpp.com/cpp-tutorial/153-exceptions-functions-and-stack-unwinding/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/153-exceptions-functions-and-stack-unwinding/#comments</comments>
		<pubDate>Sun, 05 Oct 2008 19:25:51 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
		
		<category><![CDATA[C++ Tutorial]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[call stack]]></category>

		<category><![CDATA[exceptions]]></category>

		<category><![CDATA[functions]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[stack unwinding]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=214</guid>
		<description><![CDATA[In the previous lesson on basic exception handling, we explained how throw, try, and catch work together to enable exception handling.  This lesson is dedicated to showing more examples of exception handling at work in various cases.
Exceptions within functions
In all of the examples in the previous lesson, the throw statements were placed directly within [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous lesson on <a href="http://www.learncpp.com/cpp-tutorial/152-basic-exception-handling/">basic exception handling</a>, we explained how throw, try, and catch work together to enable exception handling.  This lesson is dedicated to showing more examples of exception handling at work in various cases.</p>
<p><strong>Exceptions within functions</strong></p>
<p>In all of the examples in the previous lesson, the throw statements were placed directly within a try block.  If this were a necessity, exception handling would be of limited use.</p>
<p>One of the most useful properties of exception handling is that the throw statements do NOT have to be placed directly inside a try block due to the way exceptions propagate when thrown.  This allows us to use exception handling in a much more modular fashion.  We&#8217;ll demonstrate this by rewriting the square root program from the previous lesson to use a modular function.</p>
<pre name="code" class="cpp">

#include &quot;math.h&quot; // for sqrt() function
using namespace std;

// A modular square root function
double MySqrt(double dX)
{
    // If the user entered a negative number, this is an error condition
    if (dX &lt; 0.0)
        throw &quot;Can not take sqrt of negative number&quot;; // throw exception of type char*

    return sqrt(dX);
}

int main()
{
    cout &lt;&lt; &quot;Enter a number: &quot;;
    double dX;
    cin &gt;&gt; dX;

    try // Look for exceptions that occur within try block and route to attached catch block(s)
    {
        cout &lt;&lt; &quot;The sqrt of &quot; &lt;&lt; dX &lt;&lt; &quot; is &quot; &lt;&lt; MySqrt(dX) &lt;&lt; endl;
    }
    catch (char* strException) // catch exceptions of type char*
    {
        cerr &lt;&lt; &quot;Error: &quot; &lt;&lt; strException &lt;&lt; endl;
    }
}
</pre>
<p>In this program, we&#8217;ve taken the code that checks for an exception and calculates the square root and put it inside a modular function called MySqrt().  We&#8217;ve then called this MySqrt() function from inside a try block.  Let&#8217;s verify that it still works as expected:</p>
<pre>
Enter a number: -4
Error: Can not take sqrt of negative number
</pre>
<p>It does!</p>
<p>The most interesting part of this program is the MySqrt() function, which potentially raises an exception.  However, you will note that this exception is not inside of a try block!  This essentially means MySqrt is willing to say, &#8220;Hey, there&#8217;s a problem!&#8221;, but is unwilling to handle the problem itself.  It is, in essence, delegating that responsibility to its caller (the equivalent of how using a return code passes the responsibility of handling an error back to a function&#8217;s caller).</p>
<p>Let&#8217;s revisit for a moment what happens when an exception is raised.  First, the program looks to see if the exception can be handled immediately (which means it was thrown inside a try block).  If not, it immediately terminates the current function and checks to see if the caller will handle the exception.  If not, it terminates the caller and checks the caller&#8217;s caller.  Each function is terminated in sequence until a handler for the exception is found, or until main() terminates.  This process is called <strong>unwinding the stack</strong> (see the lesson on <a href="http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/">the stack and the heap</a> if you need a refresher on what the call stack is).</p>
<p>Now, let&#8217;s take a detailed look at how that applies to this program when MySqrt(-4) is called and an exception is raised.</p>
<p>First, the program checks to see if we&#8217;re immediately inside a try block within the function.  In this case, we are not.  Then, the stack begins to unwind.  First, MySqrt() terminates, and control returns to main().  The program now checks to see if we&#8217;re inside a try block.  We are, and there&#8217;s a char* handler, so the exception is handled by the try block within main().  To summarize, MySqrt() raised the exception, but the try/catch block in main() was the one who captured and handled the exception.</p>
<p>At this point, some of you are probably wondering why it&#8217;s a good idea to pass errors back to the caller.  Why not just make MySqrt() handle it&#8217;s own error?  The problem is that different applications may want to handle errors in different ways.  A console application may want to print a text message.  A windows application may want to pop up an error dialog.  In one application, this may be a fatal error, and in another application it may not.  By passing the error back up the stack, each application can handle an error from MySqrt() in a way that is the most context appropriate for it!  Ultimately, this keeps MySqrt() as modular as possible, and the error handling can be placed in the less-modular parts of the code.</p>
<p><strong>Another stack unwinding example</strong></p>
<p>Here&#8217;s another example showing stack unwinding in practice, using a larger stack.  Although this program is long, it&#8217;s pretty simple: main() calls First(), First() calls Second(), Second() calls Third(), Third() calls Last(), and Last() throws an exception.</p>
<pre name="code" class="cpp">

#include &lt;iostream&gt;
using namespace std;

void Last() // called by Third()
{
    cout &lt;&lt; &quot;Start Last&quot; &lt;&lt; endl;
    cout &lt;&lt; &quot;Last throwing int exception&quot; &lt;&lt; endl;
    throw -1;
    cout &lt;&lt; &quot;End Last&quot; &lt;&lt; endl;

}

void Third() // called by Second()
{
    cout &lt;&lt; &quot;Start Third&quot; &lt;&lt; endl;
    Last()
    cout &lt;&lt; &quot;End Third&quot; &lt;&lt; endl;
}

void Second() // called by First()
{
    cout &lt;&lt; &quot;Start Second&quot; &lt;&lt; endl;
    try
    {
        Third();
    }
    catch(double)
    {
         cerr &lt;&lt; &quot;Second caught double exception&quot; &lt;&lt; endl;
    }
    cout &lt;&lt; &quot;End Second&quot; &lt;&lt; endl;
}

void First() // called by main()
{
    cout &lt;&lt; &quot;Start First&quot; &lt;&lt; endl;
    try
    {
        Second();
    }
    catch (int)
    {
         cerr &lt;&lt; &quot;First caught int exception&quot; &lt;&lt; endl;
    }
    catch (double)
    {
         cerr &lt;&lt; &quot;First caught double exception&quot; &lt;&lt; endl;
    }
    cout &lt;&lt; &quot;End First&quot; &lt;&lt; endl;
}

int main()
{
    cout &lt;&lt; &quot;Start main&quot; &lt;&lt; endl;
    try
    {
        First();
    }
    catch (int)
    {
         cerr &lt;&lt; &quot;main caught int exception&quot; &lt;&lt; endl;
    }
    cout &lt;&lt; &quot;End main&quot; &lt;&lt; endl;

    return 0;
}
</pre>
<p>Take a look at this program in more detail, and see if you can figure out what gets printed and what doesn&#8217;t when it is run.  The answer follows:</p>
<pre>
Start main
Start First
Start Second
Start Third
Start Last
Last throwing int exception
First caught int exception
End First
End main
</pre>
<p>Let&#8217;s examine what happens in this case.  The printing of all the start statements is straightforward and doesn&#8217;t warrant further explanation.  Last() prints &#8220;Last throwing int exception&#8221; and then throws an int exception.  This is where things start to get interesting.</p>
<p>Because Last() doesn&#8217;t handle the exception itself, the stack begins to unwind.  Last() terminates immediately and control returns to the caller, which is Third().</p>
<p>Third() doesn&#8217;t handle any exceptions either, so it terminates immediately and control returns to Second().</p>
<p>Second() has a try block, and the call to Third() is within it, so the program attempts to match the exception with an appropriate catch block.  However, there are no handlers for exceptions of type int here, so Second() terminates immediately and control returns to First().</p>
<p>First() also has a try block, and the call to Second() is within it, so the program looks to see if there is a catch handler for int exceptions.  There is!  Consequently, First() handles the exception, and prints &#8220;First caught int exception&#8221;.</p>
<p>Because the exception has now been handled, control continues normally at the end of the catch block within First().  This means First() prints &#8220;End First&#8221; and then terminates normally.</p>
<p>Control returns to main().  Although main() has an exception handler for int, our exception has already been handled by First(), so the catch block within main() does not get executed.  main() simply prints &#8220;End main&#8221; and then terminates normally.</p>
<p>There are quite a few interesting principles illustrated by this program:</p>
<p>First, the immediate caller of a function that throws an exception doesn&#8217;t have to handle the exception if it doesn&#8217;t want to.  In this case, Third() didn&#8217;t handle the exception thrown by Last().  It delegated that responsibility to one of it&#8217;s callers up the stack.</p>
<p>Second, if a try block doesn&#8217;t have a catch handler for the type of exception being thrown, stack unwinding occurs just as if there were no try block at all.  In this case, Second() didn&#8217;t handle the exception either because it didn&#8217;t have the right kind of catch block.</p>
<p>Third, once an exception is handled, control flow proceeds as normal starting from the end of the catch blocks.  This was demonstrated by First() handling the error and then terminating normally.  By the time the program got back to main(), the exception had been thrown and handled already &#8212; main() had no idea there even was an exception at all!</p>
<p>As you can see, stack unwinding provides us with some very useful behavior &#8212; if a function does not want to handle an exception, it doesn&#8217;t not have to.  The exception will propagate up the stack until it finds someone who will!  This allows us to decide where in the call stack is the most appropriate place to handle any errors that may occur.</p>
<p>In the next lesson, we&#8217;ll take a look at what happens when you don&#8217;t capture an exception, and a method to prevent that from happening.</p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/154-uncaught-exceptions-catch-all-handlers-and-exception-specifiers/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle> 15.4 &#8212; Uncaught exceptions, catch-all handlers, and exception specifiers</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter15" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/up.png" align=middle> Index</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/152-basic-exception-handling/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 15.2 &#8212; Basic exception handling</a>
</td>
</tr>
</table>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~f/LearnCpp?a=Y2tPM"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=Y2tPM" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=Qc6aM"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=Qc6aM" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=SZzBm"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=SZzBm" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=XXOgm"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=XXOgm" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/153-exceptions-functions-and-stack-unwinding/feed/</wfw:commentRss>
		</item>
		<item>
		<title>15.2 — Basic exception handling</title>
		<link>http://www.learncpp.com/cpp-tutorial/152-basic-exception-handling/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/152-basic-exception-handling/#comments</comments>
		<pubDate>Sat, 04 Oct 2008 21:29:37 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
		
		<category><![CDATA[C++ Tutorial]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[exceptions]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=213</guid>
		<description><![CDATA[In the previous lesson on introduction to exceptions, we talked about how using return codes causes you control flow and error flow to be intermingled, constraining both.  Exceptions in C++ are implemented using three keywords that work in conjunction with each other: throw, try, and catch.
Throwing exceptions
We use signals all the time in real [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous lesson on <a href="">introduction to exceptions</a>, we talked about how using return codes causes you control flow and error flow to be intermingled, constraining both.  Exceptions in C++ are implemented using three keywords that work in conjunction with each other: <strong>throw</strong>, <strong>try</strong>, and <strong>catch</strong>.</p>
<p><strong>Throwing exceptions</strong></p>
<p>We use signals all the time in real life to note that particular events have occurred.  For example, during American football, if a player has committed a foul, the referee will throw a flag on the ground and whistle the play dead.  A penalty is then assessed and executed.  Once the penalty has been taken care of, play generally resumes as normal.</p>
<p>In C++, a <strong>throw statement</strong> is used to signal that an exception or error case has occurred (think of throwing a penalty flag).  Signaling that an exception has occurred is also commonly called <strong>raising</strong> an exception.</p>
<p>To use a throw statement, simply use the throw keyword, followed by a value of any data type you wish to use to signal that an error has occurred.  Typically, this value will be an error code, a description of the problem, or a custom exception class.</p>
<p>Here are some examples:</p>
<pre name="code" class="cpp">

throw -1; // throw a literal integer value
throw ENUM_INVALID_INDEX; // throw an enum value
throw &quot;Can not take square root of negative number&quot;; // throw a literal char* string
throw dX; // throw a double variable that was previously defined
throw MyException(&quot;Fatal Error&quot;); // Throw an object of class MyException
</pre>
<p>Each of these statements acts a signal that some kind of problem that needs to be handled has occurred.</p>
<p><strong>Looking for exceptions</strong></p>
<p>Throwing exceptions is only one part of the exception handling process.  Let&#8217;s go back to our American football analogy: once a referee has thrown a penalty flag, what happens next?  The players notice that a penalty has occurred and stop play.  The normal flow of the football game is disrupted.</p>
<p>In C++, we use the <strong>try</strong> keyword to define a block of statements (called a <strong>try block</strong>).  The try block acts as an observer, looking for any exceptions that are thrown by statements within the try block.</p>
<p>Here&#8217;s an example of an try block:</p>
<pre name="code" class="cpp">

try
{
    // Statements that may throw exceptions you want to handle now go here
    throw -1;
}
</pre>
<p>Note that the try block doesn&#8217;t define HOW we&#8217;re going to handle the exception.  It merely tells the program, &#8220;Hey, if you see an exception in the following code, grab it!&#8221;.</p>
<p><strong>Handling exceptions</strong></p>
<p>Finally, the end of our American football analogy: After the penalty has been called and play has stopped, the referee assesses the penalty and executes it.  In other words, the penalty must be handled before normal play can resume.</p>
<p>Actually handling exceptions is the job of the catch block(s).  The <strong>catch</strong> keyword is used to define a block of code (called a <strong>catch block</strong>) that handles exceptions for a single data type.</p>
<p>Here&#8217;s an example of a catch block:</p>
<pre name="code" class="cpp">

catch (int)
{
    // Handle an exception of type int here
    cerr &lt;&lt; &quot;We caught an exception of type int&quot; &lt;&lt; endl;
}
</pre>
<p>Try blocks and catch blocks work together &#8212; A try block detects any exceptions that are thrown by statements within the try block, and routes them to the appropriate catch block for handling.  A try block must have at least one catch block attached to it, but may have multiple catch blocks listed in sequence:</p>
<pre name="code" class="cpp">

int main()
{
    try
    {
        // Statements that may throw exceptions you want to handle now go here
        throw -1;
    }
    catch (int)
    {
        // Any exceptions of type int thrown within the above try block get sent here
        cerr &lt;&lt; &quot;We caught an exception of type int&quot; &lt;&lt; endl;
    }
    catch (double)
    {
        // Any exceptions of type double thrown within the above try block get sent here
        cerr &lt;&lt; &quot;We caught an exception of type double&quot; &lt;&lt; endl;
    }

    return 0;
}
</pre>
<p><strong>Putting throw, try, and catch together</strong></p>
<p>Running the above try/catch block would produce the following result:</p>
<pre>
We caught an exception of type int
</pre>
<p>A throw statement was used to raise an exception with the value -1, which is of type int.  The try block routed the int exception to the catch block that handles exceptions of type int, which then printed the error message.</p>
<p><strong>Exception handling behind the scenes</strong></p>
<p>Let&#8217;s talk about what happens behind the scenes in a little more detail.  Exception handling is actually quite simple, and the following two paragraphs are all you really need to know about it:</p>
<p>When an exception is raised (using <strong>throw</strong>), execution of the program immediately jumps to the nearest enclosing <strong>try</strong> block (propagating up the stack if necessary).  If any of the <strong>catch</strong> handlers attached to the try block handle that type of exception, that handler is executed and the exception is considered handled.</p>
<p>If no appropriate catch handlers exist, execution of the program propagates to the next enclosing try block.  If no appropriate catch handlers can be found before the end of the program, the program will fail with an exception error.</p>
<p>That&#8217;s really all there is to it.  The rest of this chapter will be dedicated to showing examples of these principles at work.</p>
<p><strong>Exceptions are handled immediately</strong></p>
<p>Here&#8217;s a short program that demonstrates how exceptions are handled immediately:</p>
<pre name="code" class="cpp">

int main()
{
    try
    {
        throw 4.5; // throw exception of type double
        cout &lt;&lt; &quot;This never prints&quot; &lt;&lt; endl;
    }
    catch(double dX) // handle exception of type double
    {
        cerr &lt;&lt; &quot;We caught a double of value: &quot; &lt;&lt; dX &lt;&lt; endl;
    }
}
</pre>
<p>This program is about as simple as it gets.  Here&#8217;s what happens: the throw statement is the first statement that gets executed &#8212; this causes an exception of type double to be raised.  Execution immediately moves to the nearest enclosing try block, which is the only try block in this program.  The catch handlers are then checked to see if any handlers matche.  Our exception is of type double, so we&#8217;re looking for a catch handler of type double.  We have one, so it executes.</p>
<p>Consequently, the result of this program is as follows:</p>
<pre>
We caught a double of value: 4.5
</pre>
<p>Note that the cout statement never executed, because the exception caused the execution path to change to the exception handler for doubles.</p>
<p><strong>A more realistic example</strong></p>
<p>Let&#8217;s take a look at an example that&#8217;s not quite so academic:</p>
<pre name="code" class="cpp">

#include &quot;math.h&quot; // for sqrt() function
using namespace std;

int main()
{
    cout &lt;&lt; &quot;Enter a number: &quot;;
    double dX;
    cin &gt;&gt; dX;

    try // Look for exceptions that occur within try block and route to attached catch block(s)
    {
        // If the user entered a negative number, this is an error condition
        if (dX &lt; 0.0)
            throw &quot;Can not take sqrt of negative number&quot;; // throw exception of type char*

        // Otherwise, print the answer
        cout &lt;&lt; &quot;The sqrt of &quot; &lt;&lt; dX &lt;&lt; &quot; is &quot; &lt;&lt; sqrt(dX) &lt;&lt; endl;
    }
    catch (char* strException) // catch exceptions of type char*
    {
        cerr &lt;&lt; &quot;Error: &quot; &lt;&lt; strException &lt;&lt; endl;
    }
}
</pre>
<p>In this code, the user is asked to enter a number.  If they enter a positive number, the if statement does not execute, no exception is thrown, and the square root of the number is printed.  Because no exception is thrown in this case, the code inside the catch block never executes.  The result is something like this:</p>
<pre>
Enter a number: 9
The sqrt of 9 is 3
</pre>
<p>If the user enters a negative number, we throw an exception of type char*.  Because we&#8217;re within a try block and a matching exception handler is found, control immediately transfers to the char* exception handler.  The result is:</p>
<pre>
Enter a number: -4
Error: Can not take sqrt of negative number
</pre>
<p>By now, you should be getting the basic idea behind exceptions.  In the next lesson, we&#8217;ll do quite a few more examples to show how flexible exceptions are.</p>
<p><strong>Multiple statements within a try block</strong></p>
<p>In the lesson on <a href="http://www.learncpp.com/cpp-tutorial/151-the-need-for-exceptions/">the need for exceptions</a>, we showed an example of one case where return codes don&#8217;t work very well:</p>
<pre name="code" class="cpp">

    std::ifstream fSetupIni(&quot;setup.ini&quot;); // open setup.ini for reading
    if (!fSetupIni)
        return ERROR_OPENING_FILE; // Some enum value indicating error

    // Note that error handling and actual code logic are intermingled

    if (!ReadParameter(fSetupIni, m_nFirstParameter))
        return ERROR_PARAMETER_MISSING; // Some other enum value indicating error
    if (!ReadParameter(fSetupIni, m_nSecondParameter))
        return ERROR_PARAMETER_MISSING; // Some other enum value indicating error
    if (!ReadParameter(fSetupIni, m_nThirdParameter))
        return ERROR_PARAMETER_MISSING; // Some other enum value indicating error
</pre>
<p>In this code, ReadParameter() is returning a boolean value indicating success or failure.  We end up having to check the return code from each call to ReadParameter() to ensure that it succeeded before proceeding.  This leads to code that is messy and redundant.</p>
<p>Let&#8217;s rewrite this snippet of code using a new version of ReadParameter() throws an int exception on failure instead of returning a boolean value:</p>
<pre name="code" class="cpp">

    std::ifstream fSetupIni(&quot;setup.ini&quot;); // open setup.ini for reading
    if (!fSetupIni)
        return ERROR_OPENING_FILE; // Some enum value indicating error

    // Read parameters and return an error if the parameter is missing
    try
    {
        // Here&#039;s all the normal code logic
        m_nFirstParameter = ReadParameter(fSetupIni);
        m_nSecondParameter = ReadParameter(fSetupIni);
        m_nThirdParameter = ReadParameter(fSetupIni);
    }
    catch (int) // Here&#039;s the error handling, nicely separated
    {
        return ERROR_PARAMETER_MISSING; // Some other enum value indicating error
    }
</pre>
<p>Note how much easier this is to read!  If any of the calls to ReadParameter() throws an exception, that exception will be caught and routed to the int exception handler, which returns an error enum to the caller.</p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/153-exceptions-functions-and-stack-unwinding/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle> 15.3 &#8212; Exceptions, functions, and stack unwinding</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter15" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/up.png" align=middle> Index</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/151-the-need-for-exceptions/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 15.1 &#8212; The need for exceptions</a>
</td>
</tr>
</table>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~f/LearnCpp?a=icqZM"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=icqZM" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=Mvc0M"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=Mvc0M" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=eTU9m"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=eTU9m" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=cA0em"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=cA0em" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/152-basic-exception-handling/feed/</wfw:commentRss>
		</item>
		<item>
		<title>15.1 — The need for exceptions</title>
		<link>http://www.learncpp.com/cpp-tutorial/151-the-need-for-exceptions/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/151-the-need-for-exceptions/#comments</comments>
		<pubDate>Sat, 04 Oct 2008 21:26:39 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
		
		<category><![CDATA[C++ Tutorial]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[error codes]]></category>

		<category><![CDATA[exceptions]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[return values]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=212</guid>
		<description><![CDATA[In the previous lesson on handling errors, we talked about ways to use assert(), cerr(), and exit() to handle errors.  However, we punted on one further topic that we will now cover: exceptions.
When return codes fail
When writing reusable code, error handling is a necessity.  One of the most common ways to handle potential [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous lesson on <a href="http://www.learncpp.com/cpp-tutorial/712-handling-errors-assert-cerr-exit-and-exceptions/">handling errors</a>, we talked about ways to use assert(), cerr(), and exit() to handle errors.  However, we punted on one further topic that we will now cover: exceptions.</p>
<p><strong>When return codes fail</strong></p>
<p>When writing reusable code, error handling is a necessity.  One of the most common ways to handle potential errors is via return codes.  For example:</p>
<pre name="code" class="cpp">

int FindFirstChar(const char* strString, char chChar)
{
    // Step through each character in strString
    for (int nIndex=0; nIndex &lt; strlen(strString); nIndex++)
        // If the charater matches chChar, return it&#039;s index
        if (strString[nIndex] == chChar)
            return nIndex;

    // If no match was found, return -1
    return -1;
}
</pre>
<p>This function returns the index of the first character matching chChar within strString.  If the character can not be found, the function returns -1 as an error indicator.</p>
<p>The primary virtue of this approach is that it is extremely simple.  However, using return codes has a number of drawbacks which can quickly become apparent when used in non-trivial cases:</p>
<p>First, return values can be cryptic &#8212; if a function returns -1, is it trying to indicate an error, or is that actually a valid return value?  It&#8217;s often hard to tell without digging into the guts of the function.</p>
<p>Second, functions can only return one value, so what happens when you need to return both a function result and an error code?  Consider the following function:</p>
<pre name="code" class="cpp">

double Divide(int nX, int nY)
{
    return static_cast&lt;double&gt;(nX)/nY;
}
</pre>
<p>This function is in desperate need of some error handling, because it will crash if the user passes in 0 for nY.  However, it also needs to return the result of nX/nY.  How can it do both?  The most common answer is that either the result or the error handling will have to be passed back as a reference parameter, which makes for ugly code that is less convenient to use.  For example:</p>
<pre name="code" class="cpp">

double Divide(int nX, int nY, bool &amp;bSuccess)
{
    if (nY == 0)
    {
        bSuccess = false;
        return 0.0;
    }

    bSuccess = true;
    return static_cast&lt;double&gt;(nX)/nY;
}

int main()
{
    bool bSuccess; // we must now pass in a bSuccess
    double dResult = Divide(5, 3, bSuccess);

    if (!bSuccess) // and check it before we use the result
        cerr &lt;&lt; &quot;An error occurred&quot; &lt;&lt; endl;
    else
        cout &lt;&lt; &quot;The answer is &quot; &lt;&lt; dResult &lt;&lt; endl;
}
</pre>
<p>Third, in sequences of code where many things can go wrong, error codes have to be checked constantly.  Consider the following code that involves parsing a text file for values that are supposed to be there:</p>
<pre name="code" class="cpp">

    std::ifstream fSetupIni(&quot;setup.ini&quot;); // open setup.ini for reading
    if (!fSetupIni)
        return ERROR_OPENING_FILE; // Some enum value indicating error

    // Read parameters and return an error if the parameter is missing
    if (!ReadParameter(fSetupIni, m_nFirstParameter))
        return ERROR_PARAMETER_MISSING; // Some other enum value indicating error
    if (!ReadParameter(fSetupIni, m_nSecondParameter))
        return ERROR_PARAMETER_MISSING; // Some other enum value indicating error
    if (!ReadParameter(fSetupIni, m_nThirdParameter))
        return ERROR_PARAMETER_MISSING; // Some other enum value indicating error
</pre>
<p>Now imagine if there were twenty parameters &#8212; you&#8217;re essentially checking for an error and returning ERROR_PARAMETER_MISSING twenty times!  This makes the function harder to read.</p>
<p>Fourth, return codes do not mix with constructors very well.  What happens if you&#8217;re creating an object and something inside the constructor goes catastrophically wrong?  Constructors have no return type to pass back a status indicator, and passing one back via a reference parameter is messy and must be explicitly checked.  Furthermore, even if you do this, the object will still be created and then has to be dealt with or disposed of.</p>
<p>Finally, when an error code is returned to the caller, the caller may not always be equipped to handle the error.  If the caller doesn&#8217;t want to handle the error, it either has to ignore it (in which case it will be lost forever), or return the error up the stack to the function that called it.  This can be messy and lead to many of the same issues noted above.</p>
<p>The primary issue with return codes is that the error handling code ends up intricately linked to the normal control flow of the code.  This in turns ends up constraining both how the code is laid out, and how errors can be reasonably handled.</p>
<p><strong>Exceptions</strong></p>
<p>Exception handling provides a mechanism to decouple handling of errors or other exceptional circumstances from the typical control flow of your code.  This allows more freedom to handle errors when and however is most useful for a given situation, alleviating many (if not all) of the messiness that return codes cause.</p>
<p>In the next lesson, we&#8217;ll take a look at how exceptions work in C++.</p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/152-basic-exception-handling/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle> 15.2 &#8212; Basic exception handling</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter15" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/up.png" align=middle> Index</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/146-partial-template-specialization/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 14.6 &#8212; Partial template specialization</a>
</td>
</tr>
</table>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~f/LearnCpp?a=VPyOM"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=VPyOM" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=ZT8CM"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=ZT8CM" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=lGuBm"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=lGuBm" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=FDVjm"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=FDVjm" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/151-the-need-for-exceptions/feed/</wfw:commentRss>
		</item>
		<item>
		<title>PRE tags in comments finally fixed, I think</title>
		<link>http://www.learncpp.com/site-news/pre-tag-in-comments-finally-fixed-i-think/</link>
		<comments>http://www.learncpp.com/site-news/pre-tag-in-comments-finally-fixed-i-think/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 06:00:17 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
		
		<category><![CDATA[Site News]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=211</guid>
		<description><![CDATA[I think I finally figured out why the PRE tags weren&#8217;t rendering in comments &#8212; Wordpress was stripping them out because they weren&#8217;t in the allowed tags list.  The reason this was hard to track down is because apparently that list doesn&#8217;t apply to me (as an admin).
In any case, I&#8217;ve implemented a fix [...]]]></description>
			<content:encoded><![CDATA[<p>I think I finally figured out why the PRE tags weren&#8217;t rendering in comments &#8212; Wordpress was stripping them out because they weren&#8217;t in the allowed tags list.  The reason this was hard to track down is because apparently that list doesn&#8217;t apply to me (as an admin).</p>
<p>In any case, I&#8217;ve implemented a fix to what I&#8217;m pretty sure the issue was, so you should be able to put any code you add to the comments inside PRE tags now like the highlighted instructions say and it should actually work.</p>
<p>Hurray!</p>
<p><p><hr>
Tip: Are you printing many of the LearnCpp articles?  You can lower your printing cost by <a href="http://www.inkguides.com">comparing ink cartridge prices before buying</a>.
<br><hr></p></p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~f/LearnCpp?a=qqgvL"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=qqgvL" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=2ropL"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=2ropL" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=6asYl"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=6asYl" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=2jVTl"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=2jVTl" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/site-news/pre-tag-in-comments-finally-fixed-i-think/feed/</wfw:commentRss>
		</item>
		<item>
		<title>14.6 — Partial template specialization</title>
		<link>http://www.learncpp.com/cpp-tutorial/146-partial-template-specialization/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/146-partial-template-specialization/#comments</comments>
		<pubDate>Mon, 18 Aug 2008 02:59:03 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
		
		<category><![CDATA[C++ Tutorial]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[pointers]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[specialization]]></category>

		<category><![CDATA[templates]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=208</guid>
		<description><![CDATA[In the lesson on expression parameters and template specialization, you learned how expression parameters could be used to parametrize template classes.
Let&#8217;s take another look at the Buffer class we used in the previous example:


template &#60;typename T, int nSize&#62; // nSize is the expression parameter
class Buffer
{
private:
    // The expression parameter controls the side [...]]]></description>
			<content:encoded><![CDATA[<p>In the lesson on <a href="http://www.learncpp.com/cpp-tutorial/144-expression-parameters-and-template-specialization/">expression parameters and template specialization</a>, you learned how expression parameters could be used to parametrize template classes.</p>
<p>Let&#8217;s take another look at the Buffer class we used in the previous example:</p>
<pre name="code" class="cpp">

template &lt;typename T, int nSize&gt; // nSize is the expression parameter
class Buffer
{
private:
    // The expression parameter controls the side of the array
    T m_atBuffer[nSize];

public:
    T* GetBuffer() { return m_atBuffer; }

    T&amp; operator[](int nIndex)
    {
        return m_atBuffer[nIndex];
    }
};

int main()
{
    // declare a char buffer
    Buffer&lt;char, 10&gt; cChar10Buffer;

    // copy a value into the buffer
    strcpy(cChar10Buffer.GetBuffer(), &quot;Ten&quot;);

    return 0;
}
</pre>
<p>Now, let&#8217;s say we wanted to write a function to print out a buffer as a string.  Although we could implement this as a member function, we&#8217;re going to do it as a non-member function instead because it will make the successive examples easier to follow.</p>
<p>Using templates, we might write something like this:</p>
<pre name="code" class="cpp">

template &lt;typename T, int nSize&gt;
void PrintBufferString(Buffer&lt;T, nSize&gt; &amp;rcBuf)
{
    std::cout &lt;&lt; rcBuf.GetBuffer() &lt;&lt; std::endl;
}
</pre>
<p>This would allow us to do the following:</p>
<pre name="code" class="cpp">

int main()
{
    // declare a char buffer
    Buffer&lt;char, 10&gt; cChar10Buffer;

    // copy a value into the buffer
    strcpy(cChar10Buffer.GetBuffer(), &quot;Ten&quot;);

    // Print the value
    PrintBufferString(cChar10Buffer);
    return 0;
}
</pre>
<p>and get the following result:</p>
<pre>
Ten
</pre>
<p>Although this works, it has a design flaw.  Consider the following:</p>
<pre name="code" class="cpp">

int main()
{
    // declare an int buffer
    Buffer&lt;int, 10&gt; cInt10Buffer;

    // copy values into the buffer
    for (int nCount=0; nCount &lt; 10; nCount++)
        cInt10Buffer[nCount] = nCount;

    // Print the value?
    PrintBufferString(cInt10Buffer); // what does this mean?
    return 0;
}
</pre>
<p>This program will compile, execute, and produce the following value (or one similar):</p>
<pre>
0012FF10
</pre>
<p>What happened?  PrintBufferString() has std::cout print the value of <code>rcBuf.GetBuffer()</code>, which returns a pointer to m_atBuffer!  When the data type is a char, cout will print the array as a C-style character string, but when the data type is non-char (such as in this case), cout will print the address that the pointer is holding!</p>
<p>Obviously this case exposes a misuse of this function (as written).  Without explicitly examining the code, the programmer would not have any clue that this function does not handle non-char buffers correctly.  This is likely to lead to programming errors.</p>
<p><strong>Template specialization</strong></p>
<p>One seemingly useful way to solve this problem is to use template specialization to ensure that only arrays of type char can be passed to PrintBufferString().  As you learned in the previous lesson, template specialization allows you to define a function where all of the templated types have been resolved to a specific data type.</p>
<p>Here&#8217;s an example of how that might work here:</p>
<pre name="code" class="cpp">

void PrintBufferString(Buffer&lt;char, 10&gt; &amp;rcBuf)
{
    std::cout &lt;&lt; rcBuf.GetBuffer() &lt;&lt; std::endl;
}

int main()
{
    // declare a char buffer
    Buffer&lt;char, 10&gt; cChar10Buffer;

    // copy a value into the buffer
    strcpy(cChar10Buffer.GetBuffer(), &quot;Ten&quot;);

    // Print the value
    PrintBufferString(cChar10Buffer);
    return 0;
}
</pre>
<p>As you can see, we&#8217;ve now specialized PrintBufferString so it will only accept Buffers of type char and of length 10.  This means if we try to call PrintBufferString with an int buffer, the compiler will give us an error.</p>
<p>Although this solves the issue of making sure PrintBufferString can not be called with an int Buffer, it brings up another problem: using full template specialization means we have to explicitly define the length of the buffer this function will accept!  Consider the following example:</p>
<pre name="code" class="cpp">

int main()
{
    Buffer&lt;char, 10&gt; cChar10Buffer;
    Buffer&lt;char, 11&gt; cChar11Buffer;

    strcpy(cChar10Buffer.GetBuffer(), &quot;Ten&quot;);
    strcpy(cChar11Buffer.GetBuffer(), &quot;Eleven&quot;);

    PrintBufferString(cChar10Buffer);
    PrintBufferString(cChar11Buffer); // this will not compile

    return 0;
}
</pre>
<p>Trying to call PrintBufferString() with cChar11Buffer will not work, because cChar11Buffer is a class of type Buffer&lt;char, 11&gt;, and PrintBufferString() only accepts classes of type Buffer&lt;char, 10&gt;.  Even though Buffer&lt;char, 10&gt; and Buffer&lt;char, 11&gt; are both templated from the generic Buffer class, the different template parameters means they are treated as different classes, and can not be intermixed.</p>
<p>Although we could make a copy of PrintBufferString() that could handle Buffer&lt;char, 11&gt;, what happens when we want to call PrintBufferString() will a buffer of size 5, or 14?  We&#8217;d have to copy the function for each different Buffer size we wanted to use.</p>
<p>Obviously full template specialization is too restrictive a solution here.  The solution we are looking for is partial template specialization.</p>
<p><strong>Partial template specialization</strong></p>
<p>Partial template specialization allows us to write functions where some of the template parameters have been fully or partially resolved.  In this case, the ideal solution would be to allow PrintBufferString() to accept char Buffers of any length.  That means we have to specialize the templated data type, but leave the length in templated form.  Fortunately, partial template specialization allows us to do just that!</p>
<pre name="code" class="cpp">

template&lt;int nSize&gt;
void PrintBufferString(Buffer&lt;char, nSize&gt; &amp;rcBuf)
{
	std::cout &lt;&lt; rcBuf.GetBuffer() &lt;&lt; std::endl;
}
</pre>
<p>As you can see here, we&#8217;ve explicitly declared that this function will only work for Buffers of type char, but nSize is still a templated parameter, so it will work for char buffers of any size.  That&#8217;s all there is to it!</p>
<p>Consider the following example:</p>
<pre name="code" class="cpp">

int main()
{
    // declare an integer buffer with room for 12 chars
    Buffer&lt;char, 10&gt; cChar10Buffer;
    Buffer&lt;char, 11&gt; cChar11Buffer;

    // strcpy a string into the buffer and print it
    strcpy(cChar10Buffer.GetBuffer(), &quot;Ten&quot;);
    strcpy(cChar11Buffer.GetBuffer(), &quot;Eleven&quot;);

    PrintBufferString(cChar10Buffer);
    PrintBufferString(cChar11Buffer);

    return 0;
}
</pre>
<p>This prints:</p>
<pre>
Ten
Eleven
</pre>
<p>Just as we expect.</p>
<p><strong>Partial template specialization for pointers</strong></p>
<p>In the previous lesson on <a href="http://www.learncpp.com/cpp-tutorial/144-expression-parameters-and-template-specialization/">expression parameters and template specialization</a>, we took a look at a simple templated Storage class:</p>
<pre name="code" class="cpp">

using namespace std;

template &lt;typename T&gt;
class Storage
{
private:
    T m_tValue;
public:
    Storage(T tValue)
    {
         m_tValue = tValue;
    }

    ~Storage()
    {
    }

    void Print()
    {
        std::cout &lt;&lt; m_tValue &lt;&lt; std::endl;;
    }
};
</pre>
<p>We showed that this class had problems when template parameter T was of type char* because of the shallow copy/pointer assignment that takes place in the constructor.  In that lesson, we used full template specialization to create a specialized version of the Storage constructor for type char* that allocated memory and created an actual deep copy of tValue.  For reference, here&#8217;s the fully specialized char* Storage constructor:</p>
<pre name="code" class="cpp">

Storage&lt;char*&gt;::Storage(char* tValue)
{
    // Allocate memory to hold the tValue string
    m_tValue = new char[strlen(tValue)+1];
    // Copy the actual tValue string into the m_tValue memory we just allocated
    strcpy(m_tValue, tValue);
}
</pre>
<p>While that worked great for Storage&lt;char*&gt;, what about other pointer types?  It&#8217;s fairly easy to see that if T is any pointer type, then we run into the problem of the constructor doing a pointer assignment instead of making an actual copy of the element being pointed to.</p>
<p>Because full template specialization forces us to fully resolve templated types, in order to fix this issue we&#8217;d have to define a new specialized constructor for each and every pointer type we wanted to use Storage with!  This leads to lots of duplicate code, which as you well know by now is something we want to avoid as much as possible.</p>
<p>Fortunately, partial template specialization offers us a convenient solution.  In this case, we&#8217;ll use class partial template specialization to define a special version of Storage that works for pointer values:</p>
<pre name="code" class="cpp">

using namespace std;

template &lt;typename T&gt;
class Storage&lt;T*&gt; // this is specialization of Storage that works with pointer types
{
private:
    T* m_tValue;
public:
    Storage(T* tValue) // for pointer type T
    {
         m_tValue = new T(*tValue);
    }

    ~Storage()
    {
        delete m_tValue;
    }

    void Print()
    {
        std::cout &lt;&lt; *m_tValue &lt;&lt; std::endl;
    }
};
</pre>
<p>And an example of this working:</p>
<pre name="code" class="cpp">

int main()
{
    // Declare a non-pointer Storage to show it works
    Storage&lt;int&gt; cIntStorage(5);

    // Declare a pointer Storage to show it works
    int x = 7;
    Storage&lt;int*&gt; cIntPtrStorage(&amp;x);

    // If cIntPtrStorage did a pointer assignment on x,
    // then changing x will change cIntPtrStorage too
    x = 9;
    cIntPtrStorage.Print();

    return 0;
}
</pre>
<p>This prints the value:</p>
<pre>
7
</pre>
<p>The fact that we got a 7 here shows that cIntPtrStorage used the pointer version of Storage, which allocated it&#8217;s own copy of the int.  If cIntPtrStorage had used the non-pointer version of Storage, it would have done a pointer assignment &#8212; and when we changed the value of x, we would have changed cIntPtrStorage&#8217;s value too.</p>
<p>Using partial template class specialization to create separate pointer and non-pointer implementations of a class is extremely useful when you want a class to handle both differently, but in a way that&#8217;s completely transparent to the end-user.</p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/151-the-need-for-exceptions/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle> 15.1 &#8212; The need for exceptions</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter14" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/up.png" align=middle> Index</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/145-class-template-specialization/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 14.5 &#8212; Class template specialization</a>
</td>
</tr>
</table>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~f/LearnCpp?a=vl9CvK"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=vl9CvK" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=x30e5K"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=x30e5K" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=RVtIqk"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=RVtIqk" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=JPTYek"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=JPTYek" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/146-partial-template-specialization/feed/</wfw:commentRss>
		</item>
		<item>
		<title>14.5 — Class template specialization</title>
		<link>http://www.learncpp.com/cpp-tutorial/145-class-template-specialization/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/145-class-template-specialization/#comments</comments>
		<pubDate>Sat, 16 Aug 2008 22:25:28 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
		
		<category><![CDATA[C++ Tutorial]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[classes]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[specialization]]></category>

		<category><![CDATA[templates]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=210</guid>
		<description><![CDATA[In the previous lesson on template specialization, we saw how it was possible to specialize member functions of a template class in order to provide different functionality for specific data types.  As it turns out, it is not only possible to specialize member functions of a template class, it is also possible to specialize [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous lesson on <a href="http://www.learncpp.com/cpp-tutorial/144-expression-parameters-and-template-specialization/">template specialization</a>, we saw how it was possible to specialize member functions of a template class in order to provide different functionality for specific data types.  As it turns out, it is not only possible to specialize member functions of a template class, it is also possible to specialize an entire class!</p>
<p>Consider the case where you want to design a class that stores 8 objects.  Here&#8217;s a simplified class to do so:</p>
<pre name="code" class="cpp">

template &lt;typename T&gt;
class Storage8
{
private:
    T m_tType[8];

public:
    void Set(int nIndex, const T &amp;tType)
    {
        m_tType[nIndex] = tType;
    }

    const T&amp; Get(int nIndex)
    {
        return m_tType[nIndex];
    }
};
</pre>
<p>Because this class is templated, it will work fine for any given type:</p>
<pre name="code" class="cpp">

int main()
{
    // Define a Storage8 for integers
    Storage8&lt;int&gt; cIntStorage;

    for (int nCount=0; nCount&lt;8; nCount++)
        cIntStorage.Set(nCount, nCount);

    for (int nCount=0; nCount&lt;8; nCount++)
        std::cout &lt;&lt; cIntStorage.Get(nCount) &lt;&lt; std::endl;

    // Define a Storage8 for bool
    Storage8&lt;bool&gt; cBoolStorage;
    for (int nCount=0; nCount&lt;8; nCount++)
        cBoolStorage.Set(nCount, nCount &amp; 3);

    for (int nCount=0; nCount&lt;8; nCount++)
        std::cout &lt;&lt; (cBoolStorage.Get(nCount) ? &quot;true&quot; : &quot;false&quot;) &lt;&lt; std::endl;

    return 0;
}
</pre>
<p>This example prints:</p>
<pre>
0
1
2
3
4
5
6
7
false
true
true
true
false
true
true
true
</pre>
<p>While this class is completely functional, it turns out that the implementation of Storage8&lt;bool&gt; is much more inefficient than it needs to be.  Because all variables must have an address, and the CPU can&#8217;t address anything smaller than a byte, all variables must be at least a byte in size.  Consequently, a variable of type bool ends up using an entire byte even though technically it only needs a single bit to store its true or false value!  Thus, a bool is 1 bit of useful information and 7 bits of wasted space.  Our Storage8&lt;bool&gt; class, which contains 8 bools, is 1 byte worth of useful information and 7 types of wasted space.</p>
<p>As it turns out, using some basic bit logic, it&#8217;s possible to compress all 8 bools into a single byte, eliminating the wasted space altogether.  However, in order to do this, we&#8217;ll effectively need to essentially revamp the class, replacing the array of 8 bools with a variable that is a single byte in size.  While we could create an entirely new class to do so, this has one major downside: we have to give it a different name.  Then the programmer has to remember that Storage8&lt;T&gt; is meant for non-bool types, whereas Storage8Bool (or whatever we name the new class) is meant for bools.  That&#8217;s needless complexity we&#8217;d rather avoid.  Fortunately, C++ provides us a better method: class template specialization.</p>
<p><strong>Class template specialization</strong></p>
<p>Class template specialization allows us to specialize a template class for a particular data type (or set of data types, if there are multiple templated parameters).  In this case, we&#8217;re going to use class template specialization to write a customized version of Storage8&lt;bool&gt; that will take precedence over the generic Storage8&lt;T&gt; class.</p>
<p>Class template specializations are treated as completely independent classes, even though they are allocated in the same way as the templated class.  This means that we can change anything and everything about our specialization class, including the way it&#8217;s implemented and even the functions it makes public, just as if it were an independent class.  Here&#8217;s our specialized class:</p>
<pre name="code" class="cpp">

template &lt;&gt; // the following is a template class with no templated parameters
class Storage8&lt;bool&gt; // we&#039;re specializing Storage8 for bool
{
// What follows is just standard class implementation details
private:
    unsigned char m_tType;

public:
    void Set(int nIndex, bool tType)
    {
        // Figure out which bit we&#039;re setting/unsetting
        // This will put a 1 in the bit we&#039;re interested in turning on/off
        unsigned char nMask = 1 &lt;&lt; nIndex;

        if (tType)  // If we&#039;re setting a bit
            m_tType |= nMask;  // Use bitwise-or to turn that bit on
        else  // if we&#039;re turning a bit off
            m_tType &amp;= ~nMask;  // bitwise-and the inverse mask to turn that bit off
	}

    bool Get(int nIndex)
    {
        // Figure out which bit we&#039;re getting
        unsigned char nMask = 1 &lt;&lt; nIndex;
        // bitwise-and to get the value of the bit we&#039;re interested in
        // Then implicit cast to boolean
        return m_tType &amp; nMask;
    }
};
</pre>
<p>First, note that we start off with <code>template&lt;&gt;</code>.  The template keyword tells the compiler that what follows is templated, and the empty angle braces means that there aren&#8217;t any template parameters.  In this case, there aren&#8217;t any template parameters because we&#8217;re replacing the only template parameter (typename T) with a specific type (bool).</p>
<p>Next, we add <code>&lt;bool&gt;</code> to the class name to denote that we&#8217;re specializing a bool version of Storage8.</p>
<p>All of the other changes are just class implementation details.  You do not need to understand how the bit-logic works in order to use the class (though here&#8217;s a link to the lesson on <a href="http://www.learncpp.com/cpp-tutorial/38-bitwise-operators/">bitwise operators</a> if you want to figure it out, but need a refresher on how bitwise operators work).</p>
<p>Note that this specialization class utilizes a single unsigned char (1 byte) instead of an array of 8 bools (8 bytes).</p>
<p>Now, when we declare a class of type Storage8&lt;T&gt;, where T is not a bool, we&#8217;ll get a version stenciled from the generic templated Storage8&lt;T&gt; class.  When we declare a class of type Storage8&lt;bool&gt;, we&#8217;ll get the specialized version we just created.  Note that we have kept the publicly exposed interface of both classes the same &#8212; while C++ gives us free reign to add, remove, or change functions of Storage8&lt;bool&#038;gt as we see fit, keeping a consistent interface means the programmer can use either class in exactly the same manner.</p>
<p>We can use the exact same example as before to show both Storage8&lt;T&gt; and Storage8&lt;bool&gt; being instantiated:</p>
<pre name="code" class="cpp">

int main()
{
    // Define a Storage8 for integers (instantiates Storage8&lt;T&gt;, where T = int)
    Storage8&lt;int&gt; cIntStorage;

    for (int nCount=0; nCount&lt;8; nCount++)
        cIntStorage[nCount] = nCount;

    for (int nCount=0; nCount&lt;8; nCount++)
        std::cout &lt;&lt; cIntStorage[nCount] &lt;&lt; std::endl;

    // Define a Storage8 for bool  (instantiates Storage8&lt;bool&gt; specialization)
    Storage8&lt;bool&gt; cBoolStorage;
    for (int nCount=0; nCount&lt;8; nCount++)
        cBoolStorage.Set(nCount, nCount &amp; 3);

    for (int nCount=0; nCount&lt;8; nCount++)
        std::cout &lt;&lt; (cBoolStorage.Get(nCount) ? &quot;true&quot; : &quot;false&quot;) &lt;&lt; std::endl;

    return 0;
}
</pre>
<p>As you might expect, this prints the same result as the previous example that used the non-specialized version of Storage8&lt;bool&gt;:</p>
<pre>
0
1
2
3
4
5
6
7
0
1
2
3
4
5
6
7
false
true
true
true
false
true
true
true
</pre>
<p>It&#8217;s worth noting again that keeping the public interface between your template class and all of the specializations identical is generally a good idea, as it makes them easier to use &#8212; however, it&#8217;s not strictly necessary.</p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/146-partial-template-specialization/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle> 14.6 &#8212; Partial template specialization</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter14" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/up.png" align=middle> Index</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/144-expression-parameters-and-template-specialization/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 14.4 &#8212; Expression parameters and template specialization</a>
</td>
</tr>
</table>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~f/LearnCpp?a=MnMMZK"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=MnMMZK" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=9thiIK"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=9thiIK" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=T2KuSk"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=T2KuSk" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=vwhYQk"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=vwhYQk" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/145-class-template-specialization/feed/</wfw:commentRss>
		</item>
		<item>
		<title>14.4 — Expression parameters and template specialization</title>
		<link>http://www.learncpp.com/cpp-tutorial/144-expression-parameters-and-template-specialization/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/144-expression-parameters-and-template-specialization/#comments</comments>
		<pubDate>Fri, 20 Jun 2008 03:07:22 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
		
		<category><![CDATA[C++ Tutorial]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[expression parameters]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[template specialization]]></category>

		<category><![CDATA[templates]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=207</guid>
		<description><![CDATA[In previous lessons, you&#8217;ve learned how to use template type parameters to create functions and classes that are type independent.  However, template type parameters are not the only type of template parameters available.  Template classes (not template functions) can make use of another kind of template parameter known as an expression parameter.
Expression parameters
A [...]]]></description>
			<content:encoded><![CDATA[<p>In previous lessons, you&#8217;ve learned how to use template type parameters to create functions and classes that are type independent.  However, template type parameters are not the only type of template parameters available.  Template classes (not template functions) can make use of another kind of template parameter known as an expression parameter.</p>
<p><strong>Expression parameters</strong></p>
<p>A template expression parameter is a parameter that does not substitute for a type, but is instead replaced by a value.  An expression parameter can be any of the following:</p>
<ul>
<li>A value that has an integral type or enumeration</li>
<li>A pointer or reference to an object</li>
<li>A pointer or reference to a function</li>
<li>A pointer or reference to a class member function</li>
</ul>
<p>In the following example, we create a buffer class that uses both a type parameter and an expression parameter.  The type parameter controls the data type of the buffer array, and the expression parameter controls how large the buffer array is.</p>
<pre name="code" class="cpp">

template &lt;typename T, int nSize&gt; // nSize is the expression parameter
class Buffer
{
private:
    // The expression parameter controls the side of the array
    T m_atBuffer[nSize];

public:
    T* GetBuffer() { return m_atBuffer; }

    T&amp; operator[](int nIndex)
    {
        return m_atBuffer[nIndex];
    }
};

int main()
{
    // declare an integer buffer with room for 12 chars
    Buffer&lt;int, 12&gt; cIntBuffer;

    // Fill it up in order, then print it backwards
    for (int nCount=0; nCount &lt; 12; nCount++)
        cIntBuffer[nCount] = nCount;

    for (int nCount=11; nCount &gt;= 0; nCount&#8211;)
        std::cout &lt;&lt; cIntBuffer[nCount] &lt;&lt; &quot; &quot;;
    std::cout &lt;&lt; std::endl;

    // declare a char buffer with room for 31 chars
    Buffer&lt;char, 31&gt; cCharBuffer;

    // strcpy a string into the buffer and print it
    strcpy(cCharBuffer.GetBuffer(), &quot;Hello there!&quot;);
    std::cout &lt;&lt; cCharBuffer.GetBuffer() &lt;&lt; std::endl;

    return 0;
}
</pre>
<p>This code produces the following:</p>
<pre>
11 10 9 8 7 6 5 4 3 2 1 0
Hello there!
</pre>
<p>One noteworthy thing about the above example is that we do not have to dynamically allocate the m_atBuffer member array!  This is because for any given instance of the Buffer class, nSize is actually constant.  For example, if you instantiate a Buffer<int, 12>, the compiler replaces nSize with 12.  Thus m_atBuffer is of type int[12], which can be allocated statically.</p>
<p><strong>Template specialization</strong></p>
<p>When instantiating a template class for a given type, the compiler stencils out a copy of each templated member function, and replaces the template type parameters with the actual types used in the variable declaration.  This means a particular member function will have the same implementation details for each instanced type.  While most of the time, this is exactly what you want, occasionally there are cases where it is useful to implement a templated member function slightly different for a specific data type.  Template specialization lets you accomplish exactly this.</p>
<p>Let&#8217;s take a look at a very simple example:</p>
<pre name="code" class="cpp">

using namespace std;

template &lt;typename T&gt;
class Storage
{
private:
    T m_tValue;
public:
    Storage(T tValue)
    {
         m_tValue = tValue;
    }

    ~Storage()
    {
    }

    void Print()
    {
        std::cout &lt;&lt; m_tValue &lt;&lt; std::endl;;
    }
};
</pre>
<p>The above code will work fine for many data types:</p>
<pre name="code" class="cpp">

int main()
{
    // Define some storage units
    Storage&lt;int&gt; nValue(5);
    Storage&lt;double&gt; dValue(6.7);

    // Print out some values
    nValue.Print();
    dValue.Print();
}
</pre>
<p>This prints:</p>
<pre>
5
6.7
</pre>
<p>Now, let&#8217;s say we want double values to output in scientific notation.  To do so, we will need to use template specialization to create a specialized version of the Print() function for doubles.  This is extremely simple: simply define the specialized function outside of the class definition, replacing the template type with the specific type you wish to redefine the function for.  Here is our specialized Print() function for doubles:</p>
<pre name="code" class="cpp">

void Storage&lt;double&gt;::Print()
{
    std::cout &lt;&lt; std::scientific &lt;&lt; m_tValue &lt;&lt; std::endl;
}
</pre>
<p>When the compiler goes to instantiate Storage&lt;double&gt;::Print(), it will see we&#8217;ve already defined one, and it will use the one we&#8217;ve defined instead of stenciling out a version from the generic templated member function.</p>
<p>As a result, when we rerun the above program, it will print:</p>
<pre>
5
6.700000e+000
</pre>
<p>Now let&#8217;s take a look at another example where template specialization can be useful.  Consider what happens if we try to use our templated Storage class with datatype char*:</p>
<pre name="code" class="cpp">

int main()
{
    using namespace std;

    // Dynamically allocate a temporary string
    char *strString = new char[40];

    // Ask user for their name
    cout &lt;&lt; &quot;Enter your name: &quot;;
    cin &gt;&gt; strString;

    // Store the name
    Storage&lt;char*&gt; strValue(strString);

    // Delete the temporary string
    delete strString;

    // Print out our value
    strValue.Print(); // This will print garbage
}
</pre>
<p>As it turns out, instead of printing the name the user input, strValue.Print() prints garbage!  What&#8217;s going on here?</p>
<p>When Storage is instantiated for type char*, the constructor for Storage&lt;char*&gt; looks like this:</p>
<pre name="code" class="cpp">

Storage&lt;char*&gt;::Storage(char* tValue)
{
     m_tValue = tValue;
}
</pre>
<p>In other words, this just does a pointer assignment!  As a result, m_tValue ends up pointing at the same memory location as strString.  When we delete strString in main(), we end up deleting the value that m_tValue was pointing at!  And thus, we get garbage when trying to print that value.</p>
<p>Fortunately, we can fix this problem using template specialization.  Instead of doing a pointer copy, we&#8217;d really like our constructor to make a copy of the input string.  So let&#8217;s write a specialized constructor for datatype char* that does exactly that:</p>
<pre name="code" class="cpp">

Storage&lt;char*&gt;::Storage(char* tValue)
{
    // Allocate memory to hold the tValue string
    m_tValue = new char[strlen(tValue)+1];
    // Copy the actual tValue string into the m_tValue memory we just allocated
    strcpy(m_tValue, tValue);
}
</pre>
<p>Now when we allocate a variable of type Storage&lt;char*&gt;, this constructor will get used instead of the default one.  As a result, m_tValue will receive its own copy of strString.  Consequently, when we delete strString, m_tValue will be unaffected.</p>
<p>However, this class now has a memory leak for type char*, because m_tValue will not be deleted when the Storage variable goes out of scope.  As you might have guessed, this can also be solved by specializing the Storage&lt;char*&gt; destructor:</p>
<pre name="code" class="cpp">

Storage&lt;char*&gt;::~Storage()
{
    delete[] m_tValue;
}
</pre>
<p>Now when variables of type ~Storage&lt;char*&gt; go out of scope, the memory allocated in the specialized constructor will be deleted in the specialized destructor.</p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/145-class-template-specialization/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle>14.5 &#8212; Class template specialization</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter14" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/up.png" align=middle> Index</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/143-template-classes/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 14.3 &#8212; Template Classes</a>
</td>
</tr>
</table>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~f/LearnCpp?a=rl6EJI"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=rl6EJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=9Jup1I"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=9Jup1I" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=2yIdji"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=2yIdji" border="0"></img></a> <a href="http://feeds.feedburner.com/~f/LearnCpp?a=XexZSi"><img src="http://feeds.feedburner.com/~f/LearnCpp?i=XexZSi" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/144-expression-parameters-and-template-specialization/feed/</wfw:commentRss>
		</item>
	</channel>
</rss><!-- Dynamic Page Served (once) in 0.327 seconds -->
