How to require operator overloading in interface

JS js.mdnq at gmail.com
Fri Jul 19 06:55:46 PDT 2013


I would like to require any implementation of an interface to 
override

import std.stdio, std.cstream;

interface A
{
	void opOpAssign(string op : "^")(int c);
}

class B : A
{
	int x;
	void opOpAssign(string op : "+")(int c) { x = c; }
         // Note it uses +
}

void main(string[] argv)
{
	
	B b = new B;

	b ^= 3;
	writeln(b.x);
	din.getc();
}

but the compiler gives an error that is 3 and b are incompatible 
types.. I'm not sure if ^= is overloaded in some default way or 
what but there is no error about b not implementing the property 
OpAssign.

If I use override for opOpassign in B, dmd says it can't override 
a non-virtual function. This is a bit strange as it would seem it 
would break inheritance.


The following code produces an undefined symbol... I could make 
A.opOpAssign final but then inheritance because a casualty.

import std.stdio, std.cstream;

interface A
{
	void opOpAssign(string op)(int c) if (op == "^");
}

class B : A
{
	int x;
	void opOpAssign(string op : "^")(int c) { x = c; }
}

class C : B
{
	void opOpAssign(string op : "^")(int c) { x = c+2; }
}

void main(string[] argv)
{
	
	B b = new B;
	C c = new C;
	A a = new C;

	b ^= 3;
	writeln(b.x);
	c ^= 3;
	writeln(c.x);
	a ^= 3;

	writeln((cast(C)a).x);
	din.getc();
}


Let me guess... this is a feature of D?


More information about the Digitalmars-d-learn mailing list