title: Comparing == != in templates
body: <p>What is the correct way to perform == and != operators in template classes?
  Assume this code:</p>
  
  <pre><code>template&lt;typename T&gt;
  class C {
          T x, y;
  
          public:
          C(T a, T b) : x(a), y(b) {}
  
          bool cmp() {
                  return x == y;
          }
  
  };
  
  int main()
  {
          // OK
          C&lt;int&gt; i(1,2);
          i.cmp();
  
          // not OK
          C&lt;double&gt; d(1.0, 2.0);
          d.cmp();
  
          return 0;
  }
  </code></pre>
  
  <p>If you build it with g++ -Wfloat-equal, you'll get</p>
  
  <blockquote>
    <p>warning: comparing floating point with == or != is unsafe
    [-Wfloat-equal]</p>
  </blockquote>
  
  <p>because you can't simply compare float variables.</p>
  
  <hr>
  
  <h2>Update</h2>
  
  <p>I've solved the problem using type_traits and enable_if like this (thanks @Andrew and @OMGtechy):</p>
  
  <pre><code>#include &lt;type_traits&gt;
  #include &lt;limits&gt;
  #include &lt;cmath&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  template &lt;typename IntegralType&gt;
  typename std::enable_if&lt;std::is_integral&lt;IntegralType&gt;::value, bool&gt;::type
  equal(const IntegralType&amp; a, const IntegralType&amp; b) {
          return a == b;
  }
  
  template &lt;typename FloatingType&gt;
  typename std::enable_if&lt;std::is_floating_point&lt;FloatingType&gt;::value, bool&gt;::type
  equal(const FloatingType&amp; a, const FloatingType&amp; b) {
          return std::fabs(a-b) &lt; std::numeric_limits&lt;FloatingType&gt;::epsilon();
  }
  
  template&lt;typename T&gt;
  class C {
      T x, y;
  
      public:
      C(T a, T b) : x(a), y(b) {}
  
      bool cmp() {
          return equal(x, y);
      }
  
  };
  
  int main()
  {
      // OK
      C&lt;int&gt; i(1,2);
      cout &lt;&lt; i.cmp() &lt;&lt; endl;
  
      // not OK
      C&lt;double&gt; d(1.0, 1.0);
      cout &lt;&lt; d.cmp() &lt;&lt; endl;
  
      return 0;
  }
  </code></pre>