www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - opApply compilation woes

reply "Gary Willoughby" <dev nomad.so> writes:
Why does the following code fail to compile if the 
`writeln(value);` line is present?

public template ForeachAggregate(T)
{
	alias ForeachAggregate = int delegate(ref T) nothrow;
}

unittest
{
	import std.stdio;

	class Foo
	{
		private string[] _data = ["foo", "bar", "baz", "qux"];

		public int opApply(ForeachAggregate!(string) dg) nothrow
		{
			int result;

			for (int x = 0; x < this._data.length; x++)
			{
				result = dg(this._data[x]);

				if (result)
				{
					break;
				}
			}

			return result;
		}
	}

	auto foo = new Foo();

	foreach (string value; foo)
	{
		writeln(value);
	}
}
Jul 12 2015
parent reply "anonymous" <anonymous example.com> writes:
On Sunday, 12 July 2015 at 17:25:17 UTC, Gary Willoughby wrote:
 Why does the following code fail to compile if the 
 `writeln(value);` line is present?
The error message (formatted to be a little more readable): ---- Error: function test2.__unittestL6_1.Foo.opApply (int delegate(ref string) nothrow dg) is not callable using argument types (int delegate(ref string __applyArg0) system) ---- Note that the parameter has "nothrow", but the argument doesn't. And that's it: writeln isn't nothrow.
Jul 12 2015
parent "Gary Willoughby" <dev nomad.so> writes:
On Sunday, 12 July 2015 at 17:33:50 UTC, anonymous wrote:
 On Sunday, 12 July 2015 at 17:25:17 UTC, Gary Willoughby wrote:
 Why does the following code fail to compile if the 
 `writeln(value);` line is present?
The error message (formatted to be a little more readable): ---- Error: function test2.__unittestL6_1.Foo.opApply (int delegate(ref string) nothrow dg) is not callable using argument types (int delegate(ref string __applyArg0) system) ---- Note that the parameter has "nothrow", but the argument doesn't. And that's it: writeln isn't nothrow.
Ah right, because the body of the foreach becomes the body of the delegate. Thanks.
Jul 12 2015