what is the difference between template and mixin template
Ali Çehreli
acehreli at yahoo.com
Sun Jun 10 12:05:48 PDT 2012
On 06/10/2012 10:08 AM, Zhenya wrote:
> Hi!Today I completly understood,what I don't now what is the difference
> between template and mixin template
There is a terminology problem: there is no such thing as "mixin
templates". There are only templates.
D also has the mixin feature with two flavors:
- Mixing in template instantiations as code (this is called "template
mixins")
- Mixing in strings as code (this is called "string mixins")
>,becouse I think that this should'nt
> work.But compiler is disagree.Could anybody explain me please?
>
> import std.stdio;
>
> int x;
> template smth()
> {
> void smth(){x = 1;}
> }
That is not a very good example because it happens to be an eponymous
template.
> void main()
> {
> int x;
> mixin smth;//why it compiles? smth is a regular template
You are instantiating smth, effectively inserting a smth() function
definition right at this point in code.
> smth();
> writeln(.x);
> writeln(x);
> readln();
> }
Here is another example from a yet-untranslated chapter of mine:
template PointArrayFeature(T, size_t count)
{
import std.stdio;
T[count] points;
void setPoint(size_t index, T point)
{
points[index] = point;
}
void printPoints()
{
writeln("All of the points:");
foreach (i, point; points) {
write(i, ":", point, ' ');
}
writeln();
}
}
That template defines a feature that combines three pieces of code:
1) An array of points of any type
2) The function setPoint() as a setter
3) The function printPoints()
Such a feature can be mixed in at any point in the program. For example,
the Line struct needs two points of type int:
struct Line
{
mixin PointArrayFeature!(int, 2);
}
The Line struct can in turn be used in the program with all the features
that it has gained by mixing in the PointArrayFeature template:
void main()
{
auto line = Line();
line.setPoint(0, 100);
line.setPoint(1, 200);
line.printPoints();
}
Ali
--
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html
More information about the Digitalmars-d-learn
mailing list