Distinguishing between const and non-const variable in a template?
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Thu Feb 22 16:41:08 PST 2007
renoX wrote:
> mario pernici a écrit :
>> 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.
>
> Mmm; how could s doesn't exist?
> D is supposed to be a statically typed language..
>
> renoX
version (Something) import some.convoluted.library;
else import some.limited.standIn;
// ... much later in module
static if(is(typeof(someSymbolNotInStandIn))) {
// ... do things usual way
}
else {
// ... do it a work-around way for the stand in's case
}
-- Chris Nicholson-Sauls
More information about the Digitalmars-d-learn
mailing list