Partial template function specialization

Steven Schveighoffer schveiguy at yahoo.com
Thu Aug 20 07:39:34 PDT 2009


On Thu, 20 Aug 2009 10:22:00 -0400, Peter Alexander  
<peter.alexander.au at gmail.com> wrote:

> Lars T. Kyllingstad Wrote:
>
>> Disclaimer: You didn't say whether you use D1 or D2, but I use D2, so
>> I'll give my answer in D2 code. It is highly likely it will also work  
>> in D1.
>
> I'm using neither :)  I'm just considering learning at the moment.
>
>
>> First of all, I don't know how it is in C++, but in D you rarely write
>> function declarations without definitions. So unless you have a very
>> general function body for your "general case", I'd simply drop it. If
>> you have, the general case looks like this:
>>
>>  <snip>
>>
>> For more info, check out http://www.digitalmars.com/d/2.0/template.html
>>
>> -Lars
>
> Excellent! Thanks a lot. I was hoping that D could overcome this problem.
>
>
> Ah, one (maybe) final question:
>
> Is there an equivalent to friends in D (didn't see any in the docs)? If  
> so, do they work with templates easily?

The module system is the way to get comparable, if not equivalent,  
behavior.  Any functions or classes declared in the same module are  
automatically friends with eachother.

The idea behind it is that a single module is generally developed as a  
group of related items, and so the functions existing in the same module  
usually know the internals of the objects inside the module.  Plus the  
author of such functions obviously has access to the source code, and  
generally is the author of the objects.

> In my style of programming, I very rarely use member functions (I think  
> they are an atrocity in language design), so I create global functions  
> for almost everything, and when they need to access to private members,  
> I have the class declare the function as a friend.
>
> Does D support my style of programming?

Yes, global functions declared in the same module of the class have full  
access to private variables.

> Here's a concrete example of something I'd like to do (pseudocode):
>
> class Foo { private int x; friend globalFun; }
> class Bar { private int y; friend globalFun; }
>
> void globalFun(ref Foo foo, ref Bar bar) { foo.x = bar.y; }
>
> Is there anything like this in D? Export sounds like the right thing,  
> but can that be used in the example above, assuming that Foo and Bar are  
> in separate modules?

You would have to put Foo and Bar in the same module along with globalFun,  
or declare their members as package, and put their modules in the same  
package.

-Steve


More information about the Digitalmars-d-learn mailing list