global vs context variable
Artur Skawina
art.08.09 at gmail.com
Wed Dec 11 08:10:18 PST 2013
On 12/11/13 09:21, luka8088 wrote:
> Hi everyone!
>
> I would like to address the issue of global variables (or states). In
> general my opinion is that they are bad solely because they (in most
> cases) lack the ability of alternative values (or states) or ability to
> alter them in user friendly way.
>
> For example, take write function from std.stdio. For a third party
[...]
> void writeOutput () {
> writeln("example output");
> }
>
> void main () {
> writeOutput();
>
> standardOutputContext(file("example.txt"), {
> writeOutput();
> });
> }
import std.stdio;
void writeOutput () {
writeln("example output");
}
void main () {
writeOutput();
{
auto ex = Push!stdout(File("example.txt", "w"));
writeOutput();
}
writeOutput();
}
struct Push(alias A, T=typeof(A)) {
T old;
this(T a) { old = A; A = a; }
~this() { A = old; }
}
Last time I checked, 'with' was still broken (the object is destroyed
too soon), but once that is fixed you should be able to do:
with (Push!stdout(File("example.txt", "w")))
writeOutput();
artur
More information about the Digitalmars-d
mailing list