Performing the usual arithmetic conversions for my own function?
<p>This came up at work today, so I thought I would throw it out to the community.</p>

<p>A co-worker wrote the following code (more or less):</p>

<pre><code>#include &lt;algorithm&gt;

double chop(double x) {
    return std::max(0, x);
}
</code></pre>

<p>But this does not even compile, because <code>std::max</code> wants both of its arguments to have the exact same type.  I believe this is so it can take a pair of references and return a reference, which is very likely what you want if you invoke it on a user-defined type.  Fair enough.</p>

<p>The fix, of course, is to use <code>std::max(0.0, x)</code>.</p>

<p>Now bear with me for a moment, because I lied.  What my coworker actually wrote was this:</p>

<pre><code>// Included from a very old header file written by someone long gone
template&lt;class T1, class T2&gt;
inline T1 myMax(T1 x, T2 y) {
    return (x &lt; y) ? y : x;
}

double chop(double x) {
    return myMax(0, x);
}
</code></pre>

<p>This compiles!  But it produces rather surprising results for x equal to, say, 0.25.  I am not sure how long it took him to find the problem, and even after finding it, he had to ask why it was not working.</p>

<p>My answer was (a) Use 0.0 instead of 0 (which fixes the bug), and (b) use <code>std::max</code> instead of <code>myMax</code> (whose behavior is quite frightening when you think about it).</p>

<p>But he is wondering why that has to be.  I mean, he can write <code>0 + x</code> or <code>0 * x</code> or <code>0 - x</code>, so why not <code>myMax(0, x)</code>?</p>

<p>Here is my first pass at giving him what he wants:</p>

<pre><code>// this is from the .hh file

// template meta-program to compute the "wider" of two types given as argument
template&lt;class T1, class T2&gt;
struct WiderType {
};

// Partial specialization for case where both types are same
template&lt;class T&gt;
struct WiderType&lt;T, T&gt; {
  typedef T type;
};

// Specialization for first type "int" and second type "double"
template&lt;&gt;
struct WiderType&lt;int, double&gt; {
  typedef double type;
};

template&lt;class T1, class T2&gt;
inline typename WiderType&lt;T1,T2&gt;::type
myMax(T1 a, T2 b) {
  return ((a &lt; b) ? b : a);
}


// this is from the .cc file

double chop(double x) {
  return myMax(0, x);
}

// just to show this still works
int chop(int x) {
  return myMax(0, x);
}
</code></pre>

<p>Now, I could go through and add a specialization for <code>WiderType</code> for every pair of integral types, plus some to do the other Usual Arithmetic Conversions.  (And I guess I could rename it <code>UsualConversions</code> or somesuch.)</p>

<p>But is there an easier way?  That is, does the C++ language give me a simple way to define my own function that performs the same conversions on its arguments as the various built-in arithmetic operators?</p>
