std_exception.html#enforce: example does not compile
kdevel
kdevel at vogtner.de
Sat Jan 27 13:29:00 UTC 2018
https://dlang.org/phobos/std_exception.html#enforce and also
https://dlang.org/library/std/exception/enforce.html present this
example:
---
auto f = enforce(fopen("data.txt"));
auto line = readln(f);
enforce(line.length, "Expected a non-empty line.");
---
fopen, readln and enforce need imports, fopen needs a mode
parameter:
enforce.d
---
import core.stdc.stdio : fopen;
import std.stdio : readln;
import std.exception;
void main ()
{
auto f = enforce(fopen("data.txt", "r"));
auto line = readln(f);
enforce(line.length, "Expected a non-empty line.");
}
---
$ dmd enforce
enforce.d(7): Error: function expected before (), not module
enforce of type void
According to https://tour.dlang.org/tour/en/basics/exceptions I
changed the import (not knowing why):
enforce.d
---
import core.stdc.stdio : fopen;
import std.stdio : readln;
import std.exception : enforce;
void main ()
{
auto f = enforce(fopen("data.txt", "r"));
auto line = readln(f);
enforce(line.length, "Expected a non-empty line.");
}
---
Now I get:
$ dmd enforce
enforce.d(8): Error: template std.stdio.readln cannot deduce
function from argument types !()(shared(_IO_FILE)*), candidates
are:
/.../dmd2/linux/bin64/../../src/phobos/std/stdio.d(3921):
std.stdio.readln(S = string)(dchar terminator = '\x0a') if
(isSomeString!S)
/.../dmd2/linux/bin64/../../src/phobos/std/stdio.d(3955):
std.stdio.readln(C)(ref C[] buf, dchar terminator = '\x0a') if
(isSomeChar!C && is(Unqual!C == C) && !is(C == enum))
/.../dmd2/linux/bin64/../../src/phobos/std/stdio.d(3962):
std.stdio.readln(C, R)(ref C[] buf, R terminator) if
(isSomeChar!C && is(Unqual!C == C) && !is(C == enum) &&
isBidirectionalRange!R && is(typeof(terminator.front ==
(dchar).init)))
What's wrong here? And why is the "selective import" of enforce
necessary?
More information about the Digitalmars-d-learn
mailing list