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, whic
The answer of Logan Capaldo is correct but can be marginally simplified because it is unnecessary to specialize the class every time. One can write:
// in header
template<typename T>
struct TypeParseTraits
{ static const char* name; };
// in c-file
#define REGISTER_PARSE_TYPE(X) \
template <> const char* TypeParseTraits<X>::name = #X
REGISTER_PARSE_TYPE(int);
REGISTER_PARSE_TYPE(double);
REGISTER_PARSE_TYPE(FooClass);
// etc...
This also allows you to put the REGISTER_PARSE_TYPE instructions in a C++ file...
As mentioned by Bunkar typeid(T).name is implementation defined.
To avoid this issue you can use Boost.TypeIndex library.
For example:
boost::typeindex::type_id<T>().pretty_name() // human readable
I just leave it there. If someone will still need it, then you can use this:
template <class T>
bool isString(T* t) { return false; } // normal case returns false
template <>
bool isString(char* t) { return true; } // but for char* or String.c_str() returns true
.
.
.
This will only CHECK type not GET it and only for 1 type or 2.
As a rephrasing of Andrey's answer:
The Boost TypeIndex library can be used to print names of types.
Inside a template, this might read as follows
#include <boost/type_index.hpp>
#include <iostream>
template<typename T>
void printNameOfType() {
std::cout << "Type of T: "
<< boost::typeindex::type_id<T>().pretty_name()
<< std::endl;
}