c – 具有隐式转换的模板类外部的运算符重载

c – 具有隐式转换的模板类外部的运算符重载,第1张

概述我有一个像这样定义的模板类 template<class T> class Wrap{ /* ... */public: Wrap(const T&); /* other implicit conversions */ /* ... */}; 我想在类之外为这个类定义所有比较运算符 template<typename T> bool operator == 我有一个像这样定义的模板类
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}
总结

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

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1241135.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存