C style 'static' functions

EnterYourNameHere via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 19 04:17:07 PDT 2017


On Wednesday, 19 July 2017 at 07:22:48 UTC, John Burton wrote:
> In C I can declare a function 'static' and it's only visible 
> from within that implementation file. So I can have a static 
> function 'test' in code1.c and another non static function 
> 'test' in utils.c and assuming a suitable prototype I can use 
> 'test' in my program and the one in code1.c will not interfere.
>
> In D it seems that declaring functions as static in a module 
> does not affect visibility outside of a module.

Indeed, static is not a visibility attribute and for a free 
function static is mostly a no-op. So far i've only seen a 
meaningful static free func once and it was used as template 
value parameter.

> So if I declare a static function in one module with a specific 
> name that is just used in internally for the implementation, 
> and then define a function with the same name in another module 
> that is intended to by 'exported' then in my main program they 
> still conflict and I have to take steps to avoid this.
>
> It looked as if I could use 'private' instead of static but 
> although this prevents me from calling the "private" function, 
> it still conflicts with the one I want to call.
>
> In C++ I could use static or an anonymous namespace for 
> implementation functions, but there doesn't seem to be anything 
> similar in D.
> Is there any way to achieve what I want in D (Private 
> implementation functions)

If what you want is an overload that has the same signature, 
which is not really possible, then you'd rather use a function 
template:

     enum Internal
     {
        no,
        yes
     }

     void foo(Internal Itr = Internal.no)()
     {
         static if (Itr) {}
         else {}
     }

That should do the trick, although i don't know the context.


More information about the Digitalmars-d-learn mailing list