www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - operator overloading and templates

reply jimmy <zsu0915 yahoo.com.tw> writes:
Hi,

I have the following code.

struct Foo(int DIM) {
	Foo!(DIM) opBinary(string op) (Foo!(DIM) rhs)
		if (op == "+" || op == "-")
	{
		return Foo!(DIM)();
	}
}

unittest {
	auto u = Foo!(2)();
	auto v = Foo!(2)();
	assert(u + v == u);
}

I got the following during my test.

Z:\proj\D\gas>rdmd --main -unittest a.d
rdmd --main -unittest a.d
a.d(12): Error: incompatible types for ((u) + (v)): 'Foo!(2)' and
'Foo!(2)'
Failed: dmd -unittest -v -o- "a.d" -I"." >a.d.deps

I have no idea why the incompatible types error occurred.
Oct 04 2011
next sibling parent Ali =?iso-8859-1?q?=C7ehreli?= <acehreli yahoo.com> writes:
On Tue, 04 Oct 2011 16:24:52 +0000, jimmy wrote:

 Hi,
 
 I have the following code.
 
 struct Foo(int DIM) {
 	Foo!(DIM) opBinary(string op) (Foo!(DIM) rhs)
 		if (op == "+" || op == "-")
 	{
 		return Foo!(DIM)();
 	}
 }
 
 unittest {
 	auto u = Foo!(2)();
 	auto v = Foo!(2)();
 	assert(u + v == u);
 }
 
 I got the following during my test.
 
 Z:\proj\D\gas>rdmd --main -unittest a.d rdmd --main -unittest a.d
 a.d(12): Error: incompatible types for ((u) + (v)): 'Foo!(2)' and
 'Foo!(2)'
 Failed: dmd -unittest -v -o- "a.d" -I"." >a.d.deps
 
 I have no idea why the incompatible types error occurred.
This doesn't answer the issue and the error message above is useless at best, but here is a workaround: Foo opBinary(string op) (Foo rhs) if (op == "+" || op == "-") { writeln("My type: ", Foo.stringof); return Foo(); } Within the template definition, the name of the template alone means "that particular instantiation of the template". Ali
Oct 04 2011
prev sibling parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Tue, 04 Oct 2011 12:24:52 -0400, jimmy <zsu0915 yahoo.com.tw> wrote:

 Hi,

 I have the following code.

 struct Foo(int DIM) {
 	Foo!(DIM) opBinary(string op) (Foo!(DIM) rhs)
 		if (op == "+" || op == "-")
 	{
 		return Foo!(DIM)();
 	}
 }

 unittest {
 	auto u = Foo!(2)();
 	auto v = Foo!(2)();
 	assert(u + v == u);
 }

 I got the following during my test.

 Z:\proj\D\gas>rdmd --main -unittest a.d
 rdmd --main -unittest a.d
 a.d(12): Error: incompatible types for ((u) + (v)): 'Foo!(2)' and
 'Foo!(2)'
 Failed: dmd -unittest -v -o- "a.d" -I"." >a.d.deps

 I have no idea why the incompatible types error occurred.
As Ali said, use Foo instead of Foo!DIM, but I think there is also a bug for this already. I just can't find it right now... -Steve
Oct 05 2011