Click here to Skip to main content
15,886,799 members
Articles / Programming Languages / C++

Using Class Templates with Fake Parameters in Derived Classes.

Rate me:
Please Sign up or sign in to vote.
3.70/5 (7 votes)
21 Aug 20079 min read 51.4K   121   14  
An article provide new C++ idom to avoid code duplication.
#include <iostream>
#include "FakeTemplateException.h"

//test customer exception
static void Test( int n );
static void catchException(int n);


//define 2 Exception classes 
struct DerivedException1_Tag {};
typedef DerivedException<DerivedException1_Tag>  DerivedException1; 

struct DerivedException2_Tag {};
typedef DerivedException<DerivedException2_Tag>  DerivedException2; 

struct DerivedException3_Tag {};
typedef DerivedException<DerivedException3_Tag>  DerivedException3; 

int main()
{
  for(int i = 1; i < 3; ++i)
    catchException(i);
  return 0;
}

void catchException(int n)
{
  try
  {
   Test(n);
  }
  catch(const DerivedException1& e1)
  { 
    std::cerr << "CATCH DerivedException1" << std::endl;
    std::cerr << e1.what()  << std::endl; 
  }
  catch(const DerivedException2& e2)
  { 
    std::cerr << "CATCH DerivedException2" << std::endl;
    std::cerr << e2.what()  << std::endl; 
  }
  return;
}

void Test( int n )
{
  switch( n)
  {
    case 1:
      {
       DerivedException1 e1;
        throw(e1);
      }
      break;
    case 2:
      {
      DerivedException2 e2("this is DerivedException2");
      throw(e2);
      }
      break;
     default:
      {
        DerivedException3 e3("this is never happen");
        throw(e3);
      }
      break;

  }
  return;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions