Free functions versus member functions

Bill Baxter dnewsgroup at billbaxter.com
Thu Oct 11 05:17:44 PDT 2007


Regan Heath wrote:
> Kris wrote:
>> Yes, that perspective resonates, though I tend to use the term 'client 
>> functions' to describe what Scott is calling non-member functions.
>>
>> There's some specific interest here with regard to D:
>>
>> 1) the Widget factory example is less clear in D, due to that lack of 
>> an equivalent 'namespace' mechanism. This is why such methods tend to 
>> reside inside the respective class/struct in D. Yes, one could perhaps 
>> use "import as" instead, but that would tend to muddy usage further. I 
>> think this indicates a minor annoyance with the D namespace mechanism. 
>> One that's bothered me from time to time <g>
> 
> What about D's modules or packages, aren't they the equivalent of a 
> namespace?  If not, what do they lack?

Two big differences with D's modules and C++ namespaces
1) A single C source file can have any number of (possibly nested) 
namespaces
2) A single namespace can be split across parts of lots of files

The result is that C++ namespaces are usually used to represent bigger 
collections of functionality.  Like "IO" or "Net".  Not 
IO.Conduit.BufferedNosePicker  They're used more for package-level 
scoping than module-level.  I don't think I have ever seen C++ code that 
uses a 1-file per 1-namespace mapping.  You certainly could do that with 
C++, but there is just no reason to.

Another difference is that in C++ you have to *explicitly* say you want 
to bring members of a namespace into your current namespace with a 
"using" directive.

In contrast, D's imports throw all the symbols into the local namespace 
by default.  You have to do something extra to prevent it ("static 
import" instead of import).

"Using" is also a nice tool for manipulating visibility of namespaces. 
D doesn't have anything quite like it.   You can say at the function 
level for instance "using SomeNamespace" and then you can use things 
from that namespace unqualified, but just to the end of that function. 
There's also a renamed using -- something like "using SNS = 
SomeNamespace;" I think.

--bb



More information about the Digitalmars-d mailing list