在C++中怎么限制模板泛型的类型

在C++中如何限制模板泛型的类型
比如说

template<class T>
class Compare
{
public:
    static bool IsEqual(const T& lh, const T& rh)
    {
        return lh == rh;
    }
};


如果我只希望仅对float和double有效,但是对其它类型都无效,应该采用什么方法?
C++ 泛型 模板

------解决方案--------------------
C++ 没有泛型约束哦, 不知道最新的 C++ 11 有没有.
如果你愿意引入 boost 库的话, 可以这样:


#include <boost/mpl/assert.hpp>
#include <boost/type_traits/is_same.hpp>

template<class T>
class Compare
{
public:
static bool IsEqual(const T& lh, const T& rh)
{
BOOST_MPL_ASSERT_MSG((boost::is_same<T, double>::value 
------解决方案--------------------
 boost::is_same<T, int>::value), type_must_be_int_or_double, (T));
return lh == rh;
}
};


不过, boost 实现这些也是依赖于特化的.
当然也可以自己封装类似的东西而不引入 boost
------解决方案--------------------
boost::enable_if 配合 type traits

用的技巧是SFINAE
------解决方案--------------------
c++0x 的话
#include <iostream>
using namespace std;

template<class T>
struct Compare {
static_assert((is_same<T, float>::value)

------解决方案--------------------
 (is_same<T, double>::value)
, "not float or double");
};

int main() {
Compare<float> c;
Compare<int> c;

cout << sizeof(c) << endl;

}

------解决方案--------------------
为什么不是header里只写声明不写实现,然后cpp里特化?

template class Compare<float>;
template class Compare<double>;

------解决方案--------------------
You need something like this:

struct Compare
{
  template<class T>
  static bool IsEqual(T t, typename std::enable_if<std::is_floating_point<T>::value, T>::type)
  {
    return true;
  }
};



Compare::IsEqual(3, 2);     // compile error
Compare::IsEqual(3.0, 2.0); // compile ok


------解决方案--------------------
如果有Concept,很容易就能做到
否则还是先用6楼或者7楼的方法吧
上面有些人只知道is_same却不知道is_floating_point,让我很是惊讶
------解决方案--------------------
引用:
比如说

C/C++ code?123456789template<class T>class Compare{public:    static bool IsEqual(const T&amp; lh, const T&amp; rh)    {        return lh == rh;    }};