Declaring run time variables
splatterdash via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Aug 4 15:18:23 PDT 2014
On Monday, 4 August 2014 at 22:09:49 UTC, anonymous wrote:
> On Monday, 4 August 2014 at 22:00:18 UTC, splatterdash wrote:
>> ```
>> File f = File("input_file")
>> // detect gzip ...
>> if (isGzip)
> {
>> auto fileIter = new MyFileReader!GzipIterator(f)
> }
>> else
> {
>> auto fileIter = new MyFileReader!NormalIterator(f)
> }
>>
>> foreach(string line; fileIter) {
>> // do things
>> }
>> ```
>
> (Added braces for clarity.)
>
>> However I always get the compiler error `undefined identifier
>> lineIter`.
>
> You have two independent variables called fileIter. Both are
> only
> available in their respective scopes. Declare the variable
> before
> the `if` to get one variable with a wider scope:
>
> SomeCommonBaseTypeOfThoseMyFileReaderVariants fileIter;
> if (isGzip)
> fileIter = new MyFileReader!GzipIterator(f);
> else
> fileIter = new MyFileReader!NormalIterator(f);
Indeed I do. I'm not sure which type I should use for the common
base type, though. MyFileReader is a templated class, so using it
plainly did not work. I also tried `InputRange!string` to no
avail despite `MyFileReader` implementing the three InputRange
requirement (popFront(), front, and empty).
Any ideas on what I should as the class?
More information about the Digitalmars-d-learn
mailing list