templates

Steven Schveighoffer schveiguy at yahoo.com
Mon Apr 19 12:16:46 PDT 2010


On Mon, 19 Apr 2010 14:16:03 -0400, Ellery Newcomer  
<ellery-newcomer at utulsa.edu> wrote:

> Hello.
>
> Say I have a [struct] template T, which takes a param S.
>
> Any T!(S) satisfies a certain template constraint W, so I can use any  
> T!(S) the same way. I want to be able to store heterogeneous T!(S) in a  
> single list. Is there any good way to express the type for this?

What you are looking for is a conversion from compile-time interface to  
runtime interface.  The only drawback is, you can't go backwards (from a  
runtime interface to a compile-time).

This can be possible in runtime reflection systems, but the theory is that  
RTTI can be built from compile-time type info.

Here is a quick-and-dirty solution, if you don't mind using  
classes/interfaces.  You are going to need some sort of runtime interface  
in order to get this to work, classes/interfaces are not the leanest way  
to do this, but it should get the job done:

The S is an extra complication that can be factored out, so let's forget  
about S for now.  Let's assume W defines a single function int foo(int).   
Let's make a W interface:

interface IW
{
    int foo(int);
}

Now, we can define a class template to hold your values:

class WByVal(T) if (implementsW!T)
{
    this(T val) {this._t = val;}
    private T _t;
    int foo(int x)
    {
       return _t.foo(x);
    }
}

Maybe a helper function

WByVal!(T) makeW(T)(T _t)
{
    return new WByVal!(T)(_t);
}

Now you can easily convert a T to a IW with makeW, and by definition, any  
IW implements the W functions, so it can be used in anything that accepts  
W by constraint.  So you can now form lists/arrays of IW objects to be  
used as needed.

One other possibility is to use a union, but I think Variant might be  
better at that point.

-Steve


More information about the Digitalmars-d-learn mailing list