Re: Comparison operator overload via base classes.
On 16 Mrz., 05:28, usenet only_tech_talk <usenet.tech.t...@gmail.com>
wrote:
Please consider :
struct A{};
template<typename T> struct B{};
struct C : B< C >{};
struct D : B< D >{};
template<typename T,typename R>
bool operator==(const B<T>&,const R&){}
template<typename T,typename L>
bool operator==(const L&,const B<T>&){}
One would hope this is all that is needed:
int main (int argc, char * const argv[]) {
A a; C c1,c2; D d1,d2;
c1 == a;
c1 == c2;
c1 == d2;
d1 == d2;
d2 == d1;
return 0;
}
but of course not (ambiguous overload). So in a second round of naive
hope, one tries:
template<typename T,typename T1>
bool operator==(const B<T>&,const B<T1>&){}
before accepting the ugly truth:
bool operator==(const C&,const C&){}
bool operator==(const D&,const D&){}
bool operator==(const C&,const D&){}
bool operator==(const D&,const C&){}
Is this the end of the road, or is there something more scalable?
I believe it should be possible to go with three overloads:
template<class T>
struct IsBaseOfB {
static const bool value = std::is_base_of<B<T>, T>::value;
};
// Use std::is_base_of from <type_traits> if your compiler
// provides that or use boost::is_base_of otherwise.
template<typename L, typename R>
typename std::enable_if<IsBaseOfB<L>::value && !IsBaseOfB<R>::value,
bool>::type
operator==(const L&, const R&){ return true; }
template<typename L, typename R>
typename std::enable_if<!IsBaseOfB<L>::value && IsBaseOfB<R>::value,
bool>::type
operator==(const L&, const R&){ return true; }
template<typename L, typename R>
typename std::enable_if<IsBaseOfB<L>::value && IsBaseOfB<R>::value,
bool>::type
operator==(const L&, const R&){ return true; }
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]