Re: how to avoid instantiation of template operator?
On Mar 25, 2:38 pm, "Daniel Kr?gler" <daniel.krueg...@googlemail.com>
wrote:
Michael Kilburn schrieb:
Basically, this operator==:
template<class T> class accessor {
typedef accessor<T> Self;
public:
template<class C> friend inline bool operator==(Self l, C& r)
{ return l.m_ref == r; }
};
should not be instantiated if 'l.m_ref == r' fails to compile due to,
for example, absence of related operator==.
Unfortunately your snippet misses some clarifications,
the obvious one is that it is not clear, what type m_ref
belongs to, because its not defined above. In the following
I assume that m_ref has type T.
The code should solve your problem, I guess. It works for
Comeau 4.3.8 ALPHA, VS2003, VS2005-SP1, and mingw
with gcc 3.4.
[template constructs]
template<class T> class accessor {
typedef accessor<T> Self;
public:
accessor() : m_ref() {}
template<class C> friend
inline
typename enable_if<IsEqualComparable<T, C>::value,
bool>::type
operator==(Self l, C& r) {
return l.m_ref == r;
}
private:
T m_ref;
};
class C{};
class D {};
bool operator==(D, D) { return true; }
bool test() {
accessor<D> a1;
D d;
bool b = a1 == d; // OK
accessor<int> a;
C c;
return a == c; // Error
}
It errors, but why all the extra constructs? It will error inside the
accessor<int> operator== anyway, in addition to erroring when you try
to return a void in test().
I think that if you're going through the trouble of defining all the
extra stuff, it should be applied toward giving a descriptive error
inside the operator== :
...
// I'm just going to make this a member:
template<class C>
bool operator==(const C & r) {
BOOST_STATIC_ASSERT(IsEqualComparable<T, C>::value);
return m_ref == r;
}
...
Unless there's something that I'm missing, which is entirely possible;
I'm somewhat of an amateur at TMP.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]