title: C++ - Cast template-type object to specific data types
body: <p>I'm using a template function <code>searchByCriteria&lt;T&gt;</code> where I would like to be able to run the function using both a <code>string</code> and a <code>double</code>. I have a list of custom-defined objects that have <code>string</code> and <code>double</code> attributes, and I would like to be able to use this function to check the criteria value (of whatever type, entered by the user), to check for matches in the object attributes of the same type.</p>
  
  <p>I.e. User enters a double value, check the object collection for matching double values. User enters a string value, check the object collection for matching string values.</p>
  
  <p>The problem I am having is once the value is entered, it is passed to another template function to be checked against the elements in the list. And at this point, the <code>T</code> object that is passed as a parameter, needs to be converted to either a double or a string to allow checking for matches.</p>
  
  <p>Here is the code for this part:</p>
  
  <pre><code>//get a sub-list of transactions
  //of all that match specified search criteria
  template &lt;typename T&gt;
  const TransactionList TransactionList::getTransactionsForSearchCriteria(T criteria) const {
      //make a copy of list to avoid deleting existing data
      TransactionList copy(*this);
      //to have appropriate transactions added in
      //then returned as copy
      TransactionList ret;
  
      //////////////////////////////////////////
      //before checking for matches can start///
      //must ID datatype of T instance//////////
      //////////////////////////////////////////
  
      //check all transactions until list empty
      while (copy.size() &gt; 0)
      {
          //check that criteria matches transaction attribute
          if (/*converted criteria matches corresponding attribute*/)
          {
              //flag as match
          }
      }
  }
  </code></pre>
  
  <p>As you can see, the parameter value <code>criteria</code> needs to be converted back into a specific data type before the while loop can be entered to check for matches. I am at a slight loss as to how to do this, as I am not aware of any casting methods in C++ that would be useful in this situation.</p>
  
  <p>The only thing I can think of would be something like:</p>
  
  <pre><code>try
  {
      //example method
      convertToDouble(criteria);
  }
  catch (SomeKindOfNumberException ex)
  {
      //cannot be a double
      //so must be string
      convertToString(criteria);
  }
  </code></pre>
  
  <p>Any help is greatly appreciated.</p>
  
  <p>Thanks,
  Mark</p>