Checking template parameter types of class

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 24 21:06:50 PDT 2015


On Monday, May 25, 2015 03:42:22 tcak via Digitalmars-d-learn wrote:
> On Monday, 25 May 2015 at 03:35:22 UTC, Jonathan M Davis wrote:
> > On Monday, May 25, 2015 03:19:29 tcak via Digitalmars-d-learn
> > wrote:
> >> Is there any syntax for something like that:
> >>
> >> class Resource(T) if( is(T: FileResource) ){
> >> }
> >>
> >>
> >> I tried it as above, but it is not accepted. Maybe I am
> >> following
> >> a wrong syntax.
> >>
> >> I tried
> >>
> >> class Resource(T: FileResource){
> >> }
> >>
> >> But it is not accepted as well.
> >
> > What about it isn't accepted? This code compiles just fine
> >
> >
> > class FileResource
> > {
> > }
> >
> > class SubFileResource : FileResource
> > {
> > }
> >
> > class Resource(T)
> >     if(is(T : FileResource))
> > {
> > }
> >
> > void main()
> > {
> >     Resource!SubFileResource foo;
> > }
> >
> > - Jonathan M Davis
>
> Well, if I do not check the line number of error, this happens.
> It was giving error on the line of creating a new instance.
>
> Line 243: auto fileResourceList = new shared FileResourceList( 2
> );
>
> main.d(243): Error: class main.FileResourceList(T) if (is(T :
> FileResource)) is used as a type

shared(FileResourceList) is not implicitly convertible to FileResource. It
may be implicitly convertible to shared(FileResource), but not
FileResource). Code that uses shared usually has to be written specifically
for shared. Also, any time that you construct a templated type, you have to
provide the template argument. IFTI (implicit function template
instantiation) doesn't work with constructors. To make that work, you need a
wrapper function - e.g.

auto resource(T)(T t)
{
    return new Resource!T(t);
}

So, I suspect that you're either running into problems, because you're using
shared, and Resource's template constraint requires non-shared, and/or
because you aren't explicitly instantiating Resource with a template
argument.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list