Hi,
Snippet:
const std = @import("std");
fn DummyInterface(comptime Impl: type) type {
return struct {
impl: *const Impl, // Implements the functionality
const Self = @This();
pub fn init(impl: *const Impl) Self { return .{ .impl = impl }; }
pub fn get_num(self: *const Self) u32 { return self.impl.get_num(); } // Delegation
};
}
const Impl5 = struct {
const Self = @This();
num: u32 = 5,
pub fn init() Self { return .{}; }
pub fn get_num(self: *const Self) u32 { return self.num; }
};
const Dummy5 = DummyInterface(Impl5); // Aims to implement the "Interface"
pub fn main() !void {
const check = struct {
fn check(dummy_if: *const DummyInterface(type)) void {
const num = dummy_if.get_num();
std.debug.print("get_num(): {}\n", .{num});
}
}.check;
const impl = Impl5.init();
const dummy = Dummy5.init(&impl);
check(&dummy);
}
I don't know the terminologies for the upper constructs, but I'd like to achieve something similar to abstract class implementation in C++ (or Interface in Java). So I create a generic struct (DummyInterface) which delegates functionality for an implementing struct (Impl5).
One of the problems that I get this error:
src/main.zig:33:11: error: expected type '*const main.DummyInterface(type)', found '*const main.DummyInterface(main.Impl5)'
check(&dummy);
^~~~~~
How could I achieve that fn check(...) could accept any "sub-types" of DummyInterface?