Generics question

D

Dilip

I boxed myself to a corner with this design. I wanted classes
implementing X to necessarily implement IEquatable. I thought I'd go
the C++ CRTP route and came up with this.

interface X<T> : IEquatable<T>
{
}

class XImpl : X<XImpl>
{
}

class XImpl_2 : X<XImpl_2>
{
}

then I had a class to manage a collection of objects implementing X

class X_Collection<T> where T : X<T>
{
private LinkedList<T> XCollection = new LinkedList<T>();
}

Now I am stuck here.

How do I declare an instance of X_Collection when I have no idea what
T would be at that point? The only thing I can do is:

class someClass
{
private X_Collection<XImpl> col = new X_Collection<XImpl>();
}

I don't want that since the whole idea is to use the X_Collection
class to keep track of *any* object that implements X<T>.

I seem to be in some kind of recursive nightmare.

Can anyone help?
 
B

Ben Voigt [C++ MVP]

Dilip said:
I boxed myself to a corner with this design. I wanted classes
implementing X to necessarily implement IEquatable. I thought I'd go
the C++ CRTP route and came up with this.

interface X<T> : IEquatable<T>
{
}

class XImpl : X<XImpl>
{
}

class XImpl_2 : X<XImpl_2>
{
}

then I had a class to manage a collection of objects implementing X

class X_Collection<T> where T : X<T>
{
private LinkedList<T> XCollection = new LinkedList<T>();
}

Now I am stuck here.

How do I declare an instance of X_Collection when I have no idea what
T would be at that point? The only thing I can do is:

class someClass
{
private X_Collection<XImpl> col = new X_Collection<XImpl>();
}

I don't want that since the whole idea is to use the X_Collection
class to keep track of *any* object that implements X<T>.

I seem to be in some kind of recursive nightmare.

Can anyone help?

According to the LSP, you can't provide a strong guarantee that you only
compare the object to the same implementation type, the comparand could be
any X, so use

interface X : IEquatable<X>
{
}

and everything should turn out ok.
 
D

Dilip

According to the LSP, you can't provide a strong guarantee that you only
compare the object to the same implementation type, the comparand could be
any X, so use

interface X : IEquatable<X>
{

}

and everything should turn out ok.

Cheers Ben! My mind has successfully disentangled itself :)
 
B

Ben Voigt [C++ MVP]

Dilip said:
Cheers Ben! My mind has successfully disentangled itself :)

I'm glad for you. Practically nothing that CRTP is good for in C++ works in
..NET, primarily because generics don't late-bind like templates.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top