Instantiating a class with range template parameter
Jon Degenhardt via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Sep 8 01:20:49 PDT 2016
I've been generalizing output routines by passing an OutputRange
as an argument. This gets interesting when the output routine is
an virtual function. Virtual functions cannot be templates, so
instead the template parameters need to be part of class
definition and specified when instantiating the class.
An example is below. It works fine. One thing I can't figure out:
how to provide the range parameter without first declaring a
variable of the appropriate type. What works is something like:
auto writer = stdout.lockingTextWriter;
auto x = new Derived!(typeof(writer));
Other forms I've tried fail to compile. For example, this fails:
auto x = new Derived!(typeof(stdout.lockingTextWriter));
I'm curious if this can be done without declaring the variable
first. Anyone happen to know?
--Jon
Full example:
import std.stdio;
import std.range;
class Base(OutputRange)
{
abstract void writeString(OutputRange r, string s);
}
class Derived(OutputRange) : Base!OutputRange
{
override void writeString(OutputRange r, string s)
{
put(r, s);
put(r, '\n');
}
}
void main()
{
auto writer = stdout.lockingTextWriter;
auto x = new Derived!(typeof(writer));
x.writeString(writer, "Hello World");
}
More information about the Digitalmars-d-learn
mailing list