运算符在模板类外部重载,具有隐式转换

use*_*535 7 c++ operator-overloading

我有一个像这样定义的模板类

template<class T> class Wrap
{
    /* ... */
public:
    Wrap(const T&);
    /* other implicit conversions */

    /* ... */
};
Run Code Online (Sandbox Code Playgroud)

我想在类之外为这个类定义所有比较运算符

template<typename T> bool operator == (const Wrap<T>&, const Wrap<T>&)
{
    // Do comparison here
}
Run Code Online (Sandbox Code Playgroud)

但是,此声明不支持隐式转换const T&或任何其他类型const Wrap<T>&.

所以我的问题是当其中一个操作数是类型Wrap<T>而另一个不是类型时,我如何使它支持隐式转换.我不想为每个可能的排列编写每个运算符的多个声明.

小智 4

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
}
Run Code Online (Sandbox Code Playgroud)