Debug help - foreach opApply overload School example: Programming in D

Brother Bill brotherbill at mail.com
Mon Aug 18 20:22:38 UTC 2025


On Monday, 18 August 2025 at 17:58:54 UTC, Dejan Lekic wrote:
> So, to fix your error, you can remove the "const" method 
> qualifier from opApply, or cast the const away from the member 
> when you use it.

Thanks for the tip.  It just needed more 'const' keywords 
sprinkled in here and there.

Here is a working example:
```
STUDENTS
Bob
Carol
Ted
Alice

TEACHERS
Mr. Smith
Dr. Kildare
Albert Einstein
```

source/app.d
```
import std.stdio;

void main() {
	auto school = new School;

	school.addStudent("Bob");
	school.addStudent("Carol");
	school.addStudent("Ted");
	school.addStudent("Alice");

	school.addTeacher("Mr. Smith");
	school.addTeacher("Dr. Kildare");
	school.addTeacher("Albert Einstein");

	writeln("STUDENTS");
	foreach (const Student student; school) {
		writeln(student.name);
	}
	writeln;

	writeln("TEACHERS");
	foreach (const Teacher teacher; school) {
		writeln(teacher.name);
	}
}

class School {
	Student[] students;
	Teacher[] teachers;

	int opApply(int delegate(ref const Student) dg) const {
		int result = 0;

		for (int i = 0; i < students.length; ++i) {
			const Student student = students[i];
			result = dg(student);
			if (result)
				break;
		}

		return result;
	}

	int opApply(int delegate(const ref Teacher) dg) const {
		int result = 0;

		for (int i = 0; i < teachers.length; ++i) {
			const Teacher teacher = teachers[i];
			result = dg(teacher);
			if (result)
				break;
		}
		return result;
	}

	void addStudent(string studentName) {
		students ~= new Student(studentName);
	}

	void addTeacher(string teacherName) {
		teachers ~= new Teacher(teacherName);
	}
}

class Student {
	string name;

	this(string name) {
		this.name = name;
	}
}

class Teacher {
	string name;

	this(string name) {
		this.name = name;
	}
}

```


More information about the Digitalmars-d-learn mailing list