A good advertisement for 'static if'

Craig Dillabaugh craig.dillabaugh at gmail.com
Thu Dec 12 20:53:56 PST 2013


On Thursday, 12 December 2013 at 17:34:13 UTC, FreeSlave wrote:
> On Thursday, 12 December 2013 at 14:55:28 UTC, Craig Dillabaugh 
> wrote:
>> I am not sure if this belongs in D.learn, but it might be of 
>> interest.  I was writing some C++ code for a project at work 
>> and have a class that stores image data from a file.  The 
>> image data can be in just about any numeric 
>> (int/float/complex) type, so I wanted a 'wrapper' class/struct 
>> that could hold any type of data without being 'parameterized' 
>> (we use templates for image access).
>>
clip
>>
>> Maybe there is a better way to do this in C++, but I thought I 
>> would post here as a case-study in the usefulness of 'static 
>> if'.
>>
>> Craig
>
> In C++ you can use partial specialization to achieve what you 
> want.
>
> class Storage
> {
> public:
>     union {
>         float* fdata;
>         int* idata;
>     } data;
> };
>
> template<typename T>
> T* get(Storage& stor)
> {
>     return 0; //or throw exception
> }
>
> template<>
> float* get<float>(Storage& stor)
> {
>     return stor.data.fdata;
> }
>
> template<>
> int* get<int>(Storage& stor)
> {
>     return stor.data.idata;
> }
>
> int main()
> {
>     Storage stor;
>     float* fdata = get<float>(stor);
>     return 0;
> }

Thanks for this suggestion, it avoids the reinterpret cast 
nicely.  I've used template specialization in other cases, but it 
didn't occur to me in this case (plus adding the 
'reinterpret_cast' required less refactoring on my part at the 
time). However, I may switch my code to use this method since the 
resulting executable should be smaller/faster since the big if 
... else statement isn't inserted with every template 
instantiation.

However neither solution is as nice as 'static if' in D.  The 
benefits of having all my type checks in one space, and the 
'dead' code is eliminated in the instantiations.

Cheers, Craig




More information about the Digitalmars-d-learn mailing list