title: C++ Get name of type in template
body: <p>I'm writing some template classes for parseing some text data files, and as such it is likly the great majority of parse errors will be due to errors in the data file, which are for the most part not written by programmers, and so need a nice message about why the app failed to load e.g. something like:</p>
  
  <blockquote>
    <p>Error parsing example.txt. Value ("notaninteger")of [MySectiom]Key is not a valid int</p>
  </blockquote>
  
  <p>I can work out the file, section and key names from the arguments passed to the template function and member vars in the class, however I'm not sure how to get the name of the type the template function is trying to convert to.</p>
  
  <p>My current code looks like, with specialisations for just plain strings and such:</p>
  
  <pre><code>template&lt;typename T&gt; T GetValue(const std::wstring &amp;section, const std::wstring &amp;key)
  {
      std::map&lt;std::wstring, std::wstring&gt;::iterator it = map[section].find(key);
      if(it == map[section].end())
          throw ItemDoesNotExist(file, section, key)
      else
      {
          try{return boost::lexical_cast&lt;T&gt;(it-&gt;second);}
          //needs to get the name from T somehow
          catch(...)throw ParseError(file, section, key, it-&gt;second, TypeName(T));
      }
  }
  </code></pre>
  
  <p>Id rather not have to make specific overloads for every type that the data files might use, since there are loads of them...</p>
  
  <p>Also I need a solution that does not incur any runtime overhead unless an exception occurs, i.e. a completely compile time solution is what I want since this code is called tons of times and load times are already getting somewhat long. </p>
  
  <p>EDIT: Ok this is the solution I came up with:</p>
  
  <p>I have a types.h containg the following</p>
  
  <pre><code>#pragma once
  template&lt;typename T&gt; const wchar_t *GetTypeName();
  
  #define DEFINE_TYPE_NAME(type, name) \
      template&lt;&gt;const wchar_t *GetTypeName&lt;type&gt;(){return name;}
  </code></pre>
  
  <p>Then I can use the DEFINE_TYPE_NAME macro to in cpp files for each type I need to deal with (eg in the cpp file that defined the type to start with).</p>
  
  <p>The linker is then able to find the appropirate template specialisation as long as it was defined somewhere, or throw a linker error otherwise so that I can add the type.</p>