Unable to instantiate template with same name as function

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Mar 3 03:34:22 PST 2016


On Thursday, March 03, 2016 14:28:25 Shriramana Sharma via Digitalmars-d-learn 
wrote:
> Hello people and thanks for your replies.
>
> Jonathan M Davis via Digitalmars-d-learn wrote:
> > You can't overload a function and an eponymous template like that. They
> > need to have distinct names.
>
> Why is it not possible for the overload to happen? After all, the compiler
> should be able to identify which to use by seeing whether it is followed by
> ! or (), no?

It's not legal to overload a variable and a function either. Only functions
can overload functions. One symbol can shadow another if one is in a smaller
scope and both aren't local variables (e.g. one is at module scope whereas
the other is a local variable), but symbols at the same scope level can only
overload if they're functions or templates with differing template
constraints, and even then, they have to be the same thing (not one a
function and the other a template). That's just the way the language is, and
it does avoid certain classes of bugs.

> > > Now, that being said, I don't understand why
> >
> > you'd need to do anything with a template for CTFE in this case. Just
> > write the function and then call it in a context that requires a
> > compile-time result, and it should work. e.g.
>
> OK but say I have a function which returns an array. If I use enum to CTFE
> its result, then it is repeatedly included explicitly in all places it is
> used, thereby using more memory. So I want to do:
>
> string s = ta!"s";
>
> Obviously, I can still do the different name approach, so it brings us back
> to the question as to why the name can't be re-used.

If you want a function to be called at compile time, then its result has to
be assigned to something that's evaluated at compile time - like an enum.
So, you can't do something like

    string s = ta("s");

and have it execute at compile time, and yes, having

    enum s = ta("s)";

and using s all over the place will result in an allocation each time that s
is used. However, you can combine the two and avoid that problem. e.g.

    enum e = ta("s");
    string s = e;

The ta is run at compile time, and it's only evaluated once. In general,
it's considered good practice to make something a function when you want to
call it at either compile time or runtime. Then if you want to force it to
be evaluated at compile time, just assign it to an enum and use that, even
if you then assign it to a variable so that it doesn't get evaluated
multiple times. But if you really want a template in addition to the
function for whatever reason, then just name the template version something
different. It may not be quite what you want, but it works just fine.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list