Static strings in templates

Leonard Dahlmann leo.dahlmann at gmail.com
Fri May 2 03:02:15 PDT 2008


Janice Caron Wrote:

> I don't know if this is a bug or not. Someone please help me out.
> Here's the deal. Suppose I declare:
> 
>     int foo(T)(T s, T t)
> 
> with the expectation that the template will be passed a couple of
> strings, wstrings or dstring. All works fine if I do
> 
>     string s;
>     string t;
>     int n = foo(s,t);
> 
> However, the template can't be instantiated with
> 
>     int n = foo("abcde","fg");
> 
> because the type of the first argument is invariant(char)[5u], and the
> type of the second argument is invariant(char)[2u], and the compiler
> can't figure out that both can (and should) be implicitly cast to
> invariant(char)[].
> 
> It occurs to me that even with only a single parameter, passing string
> literals to templated string function will lead to a lot of template
> bloat, if the template always considers the argument type to be
> invariant(char)[N] (for some N), as opposed to simply
> invariant(char)[].
> 
> Is this a bug? Can anything be done about this? Is there a workaround?

I think a workaround is to use downs' Unstatic template.
Given a static array type, it returns the corresponding dynamic array type.

    template Unstatic(T) { alias T Unstatic; }
    template Unstatic(T : T[]) { alias T[] Unstatic; }

    int foo(T)(Unstatic!(T) s, Unstatic!(T) t)




More information about the Digitalmars-d mailing list