S
Stuart Golodetz
Fernando said:Hi people,
I want to write something like this example ( C++0x )
class comparable
{
public:
bool is_equal( decltype(*this) other ) // should be X&
{
return true; // no matter
}
};
I get the following errors
MSVC10 -> Error 1 error C2355: 'this' : can only be
referenced inside non-static member functions
MinGW (GCC 4.6) -> invalid use of 'this' at top level
In the n1478.pdf paper (
http://std.dkuug.dk/jtc1/sc22/wg21/docs/papers/2003/n1478.pdf ) are examples
that use decltype with "this" keyword, but not as an argument.
class X {
void foo() {
decltype(this) // X*
decltype(*this) // X&
...
}
void bar() const {
decltype(this) // const X*
decltype(*this) // const X&
...
}
};
Sorry for the comparisons, but in the Eiffel language you can write
something like this ...
is_equal (other: like Current) : BOOLEAN
Current is the same that C++ this.
other argument will be the same type as the class where the method is
written.
I wonder whether this alternative decltype (*this) is left out for some
specific reason or if you know any other way to achieve the same result.
Thanks,
Fernando Pelliccioni.
D'oh -- just realised this was cross-posted to the moderated group
(possibly not a good idea, since the posts of anyone who accidentally
replies to both won't come through in comp.lang.c++ until they pass
moderation). For what it's worth, the reply I just sent said:
===
One way of achieving the same result here might be CRTP:
#include <iostream>
class Comparable
{
public:
virtual ~Comparable() {}
virtual bool is_equal(const Comparable& rhs) const = 0;
};
template <typename T>
class TypedComparable : public Comparable
{
public:
bool is_equal(const Comparable& rhs) const
{
const T *p = dynamic_cast<const T*>(&rhs);
if(p) return typed_is_equal(*p);
else return false;
}
virtual bool typed_is_equal(const T& rhs) const = 0;
};
class X : public TypedComparable<X>
{
private:
int m_i;
public:
X(int i)
: m_i(i)
{}
public:
bool typed_is_equal(const X& rhs) const
{
return m_i == rhs.m_i;
}
};
class Y : public TypedComparable<Y>
{
public:
bool typed_is_equal(const Y& rhs) const
{
return true;
}
};
int main()
{
X x1(23), x2(23), x3(9);
Y y;
std::cout << x1.is_equal(x2) << ' ' << x1.is_equal(x3) << ' ' <<
x1.is_equal(y) << ' ' << y.is_equal(y) << '\n';
return 0;
}
Not sure if that helps at all?
Cheers,
Stu