On Tuesday, 2 July 2013 at 18:47:00 UTC, Jesse Phillips wrote:
[..] The behavior that it [alias this] should be simulating is
inheritance, [..]
Okay. I had thought of "alias this" as *merely* implicit
conversion. But it really makes sense that it simulates (models)
inheritance and the implicit conversion (to the "base" type) is
just a consequence of that.
On Tuesday, 2 July 2013 at 18:47:00 UTC, Jesse Phillips wrote:
[..] I'd probably fail writing C++ for this so here is some D
code to translate:
import std.stdio;
class Wrap(Gift) {
abstract Gift gift();
}
class Teddy : Wrap!Teddy {
int id;
this(int i) { id = i; }
override Teddy gift() { return this; }
}
Gift tearOpen(Gift)(Wrap!Gift wrappedGift)
{
return wrappedGift.gift;
}
void main() {
auto ted = new Teddy(123);
auto r = tearOpen(ted); // NOOOO! Teddy!
assert(r == ted); // Phew, Teddy was implicitly gift-wrapped
// and we tore the wrap open, not Teddy.
}
Here's what the corresponding code would be in C++:
#include <cassert>
template <typename Gift>
class Wrap
{
public:
virtual Gift gift() = 0;
};
class Teddy : public Wrap<Teddy>
{
public:
int id;
Teddy(int i) : id(i) { }
Teddy gift() { return *this; }
bool operator==(const Teddy& other) const
{
return id == other.id;
}
};
template <typename Gift>
Gift tearOpen(Wrap<Gift>& wrappedGift)
{
return wrappedGift.gift();
}
int main()
{
auto ted = Teddy(123);
auto r = tearOpen(ted); // OK
assert(r == ted); // OK
return 0;
}