Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>No and it will not work reliable with typeid either. It will give you some internal string that depends on the compiler implementation. Something like "int", but also "i" is common for <code>int</code>.</p> <p>By the way, if what you want is to only compare whether two types are the same, you don't need to convert them to a string first. You can just do</p> <pre><code>template&lt;typename A, typename B&gt; struct is_same { enum { value = false }; }; template&lt;typename A&gt; struct is_same&lt;A, A&gt; { enum { value = true }; }; </code></pre> <p>And then do</p> <pre><code>if(is_same&lt;T, U&gt;::value) { ... } </code></pre> <p>Boost already has such a template, and the next C++ Standard will have <code>std::is_same</code> too. </p> <h2>Manual registration of types</h2> <p>You can specialize on the types like this:</p> <pre><code>template&lt;typename&gt; struct to_string { // optionally, add other information, like the size // of the string. static char const* value() { return "unknown"; } }; #define DEF_TYPE(X) \ template&lt;&gt; struct to_string&lt;X&gt; { \ static char const* value() { return #X; } \ } DEF_TYPE(int); DEF_TYPE(bool); DEF_TYPE(char); ... </code></pre> <p>So, you can use it like</p> <pre><code>char const *s = to_string&lt;T&gt;::value(); </code></pre> <p>Of course, you can also get rid of the primary template definition (and keep only the forward declaration) if you want to get a compile time error if the type is not known. I just included it here for completion. </p> <p>I used static data-members of char const* previously, but they cause some intricate problems, like questions where to put declarations of them, and so on. Class specializations like above solve the issue easily. </p> <h2>Automatic, depending on GCC</h2> <p>Another approach is to rely on compiler internals. In GCC, the following gives me reasonable results:</p> <pre><code>template&lt;typename T&gt; std::string print_T() { return __PRETTY_FUNCTION__; } </code></pre> <p>Returning for <code>std::string</code>.</p> <blockquote> <p><code>std::string print_T() [with T = std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;]</code></p> </blockquote> <p>Some <code>substr</code> magic intermixed with <code>find</code> will give you the string representation you look for. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload