Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use template specialization to get what you want.</p> <pre><code>// General template template&lt;typename T&gt; struct IsFundamentalType { enum { result = false }; }; // Template specializations for each fundamental type template&lt;&gt; struct IsFundamentalType&lt;char&gt; { enum { result = true }; }; template&lt;&gt; struct IsFundamentalType&lt;int&gt; { enum { result = true }; }; template&lt;&gt; struct IsFundamentalType&lt;short&gt; { enum { result = true }; }; template&lt;&gt; struct IsFundamentalType&lt;float&gt; { enum { result = true }; }; // And so on for other fundamental types ... class NonFundamentalType { }; template&lt;typename T&gt; void DoSomething(const T&amp; var) { if(IsFundamentalType&lt;T&gt;::result) { printf("I'm fundamental type!\n"); } else { printf("I'm not a fundamental type!\n"); } } int main() { int i = 42; char c = 42; short s = 42; float f = 42.0f; NonFundamentalType nft; DoSomething(i); DoSomething(c); DoSomething(s); DoSomething(f); DoSomething(nft); } </code></pre> <p>In this code, if you pass in a type such as <code>int</code> or <code>char</code>, the compiler will use the specialization of <code>IsFundamentalType</code> (given that you've defined the specializations for all fundamental types). Otherwise, the compiler will use the general template, as it is the case for the <code>NonFundamentalType</code> class. The important thing is that the specialized ones have a <code>result</code> member defined as <code>true</code>, while the general template also has a <code>result</code> member defined as <code>false</code>. You can then use the <code>result</code> member for the <code>if</code> statement. Optimizing compilers should be able to elide the <code>if</code> statement seeing that the expression reduces to a constant true/false value, so doing something like this should not impose a runtime penalty.</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