C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 具有隐式转换的模板类外部的运算符重载大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个像这样定义的模板类
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>类型时,我如何使它@L_874_5@隐式转换.而另一个不是.我不想为每个可能的排列编写每个运算符的多个声明.

解决方法

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
}

大佬总结

以上是大佬教程为你收集整理的c – 具有隐式转换的模板类外部的运算符重载全部内容,希望文章能够帮你解决c – 具有隐式转换的模板类外部的运算符重载所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。