Distinguishing between const and non-const variable in a template?
mario pernici
mario.pernici at mi.infn.it
Thu Feb 22 14:14:46 PST 2007
Deewiant Wrote:
> renoX wrote:
> > mario pernici a écrit :
> >> renoX Wrote:
> >>
> >>> Hello,
> >>>
> >>> I'm trying to improve format string by allowing the format
> >>> " ... %{x} ...", my problem is that when I give a non-const char[]
> >>> parameter in
> >>> mixin(Putf!(foo));
> >>>
> >>> then the template fail..
> >>>
> >>> How can I reliably detect in a template if the parameter is a
> >>> constant or not?
> > [cut]
> >>
> >> Maybe you can use something like this
> >>
> >> const char[] s = "ab";
> >> static if(is(typeof(&s))) {
> >> writefln(s, " not constant");
> >> }
> >> else {
> >> static if(is(typeof(s))) {
> >> writefln(s, " constant");
> >> }
> >> }
> >
> > Very nice, thanks!
> >
> > I'm curious: how did you find this??
> > I don't recall seeing it in the documentation and it looks kind of
> > magical to me..
> >
> > Thanks again,
> > renoX
> >
>
> He probably just figured it out: you can't take the address of a constant, so
> is(typeof(&s)) is false if s is a constant. I'm not sure about the necessity of
> the is(typeof(s)) in the else case, though.
>
I learned about static if (is(typeof(...)))
from the post by Kirk McDonald
in the recent thread
"Testing if a function is defined in a module".
The else clause static if(is(typeof(s))) is to make
sure that s exists.
More information about the Digitalmars-d-learn
mailing list