Templates class member functions not conditional?

monarch_dodra monarchdodra at gmail.com
Tue Sep 11 03:52:02 PDT 2012


This is related to:
http://d.puremagic.com/issues/show_bug.cgi?id=5193

Basically:
-------
struct S
{
   const int i;
}

struct C(T)
{
     private T val;
     @property void front(T value)
         {val = value;} //HERE
}

void main()
{
   C!S test;
}
--------

I wrote a generic template C(T), with a certain member function. 
I created an instance of that template with the parameter S.

Now, I'm getting a compile error at here, which would be 
understandable...
...*if* I was calling said member function.

In C++, member functions of templates are *only* compiled if they 
are ever called. This is not just an optimization, it is meant 
specifically to allow compiling a template, only if a certain 
amount of functionality is required, and the "not required" 
functionality wouldn't compile anyways.

Is this not the case for D? Or is it currently a limitation?
Can I ever expect we'll get a "conditionally compiled on 
requirement" functionality for template struct member functions.


Regarding making the above work, I found 2 solutions:

/////////////////////  1  /////////////////////
struct C(T)
{
     private T val;
     static if(isAssignable(T!T))
     {
         @property void front(T value)
             {val = value;}
     }
}

This works but:
a) It looks cludgy, and cumbursome on implementation
b) If I *were* to attemp a call to front, the compile error would 
be an obscure "fucntion not found", as opposed to "can't assign"

/////////////////////  2  /////////////////////
I find this more elegant: Make the member function itself a 
template:

struct C(T)
{
     private T val;
     @property void front()(T value)
         {val = value;}
}

This works, and is correctly "conditionally compiled on 
requirement". The signature is kind of kludgy, but it works... 
AND, if someone *does* attempt to make the call, then a verbose 
compile error appears.

Thoughts?


More information about the Digitalmars-d-learn mailing list