Troubles with template constraints on string and static if

Alex sascha.orlov at gmail.com
Thu Apr 26 15:26:15 UTC 2018


On Thursday, 26 April 2018 at 15:06:49 UTC, sungal wrote:
> I have this piece of code and I can't understand why the 
> `static if` conditionals are always false.
>
> ```
> import std.digest.sha;
> import std.file;
> import std.stdio;
>
> void main()
> {
>     auto hash1 = produceHash!string("prova.d");
>     auto hash2 = produceHash!File(File("./prova.d"));
> }
>
> string produceHash(Type)(Type data)
>     if(is(Type == string) || is(Type == File))
> {
>     string h;
>     static if(is(Type == File)) {
>         enforce(data.exists, "File does not exist.");
>         // Hashing both name and file, to avoid having the same 
> Hash on empty files
>         return 
> toHexString(digest!SHA256(data.byChunk(4096*1024))).dup;
>     } else static if(is(Type == string)){
>         return toHexString(digest!SHA256(data)).dup;
>     }
>     static assert(false, "Data must be string or file. ");
> }
> ```
>
> ```
> prova.d(22): Error: static assert  "Data must be string or 
> file. "
> prova.d(7):        instantiated from here: produceHash!string
> ```

The static assert is unconditionally evaluated after the static 
if/else clause. This leads to a compile time assertion failure.
Add an "else", maybe.


More information about the Digitalmars-d-learn mailing list