我有一个像这样定义的模板类
template<class T> class Wrap
{
/* ... */
public:
Wrap(const T&);
/* other implicit conversions */
/* ... */
};
我想在类之外为这个类定义所有比较运算符
template<typename T> bool operator == (const Wrap<T>&,const Wrap<T>&)
{
// Do comparison here
}
然而,该声明不支持将const T&或任何其他类型的隐式转换为const Wrap< T>&.
所以我的问题是当其中一个操作数是Wrap< T>类型时,我如何使它支持隐式转换.而另一个不是.我不想为每个可能的排列编写每个运算符的多个声明.
解决方法
template<class T> struct is_wrap : std::false_type {};
template<class T> struct is_wrap<Wrap<T>> : std::true_type {};
template<class T1,class T2> typename std::enable_if<is_wrap<typename std::common_type<T1,T2>::type>::value,bool>::type operator == (const T1& t1,const T2& t2)
{
const typename std::common_type<T1,T2>::type& tc1 = t1,tc2 = t2;
// compare with tc1 and tc2
}