Specify the type but not number of function arguments in an interface?

Jarrett Billingsley jarrett.billingsley at gmail.com
Fri Jul 3 12:01:47 PDT 2009


On Fri, Jul 3, 2009 at 2:54 PM, Doctor J<nobody at nowhere.com> wrote:
> I want to write an interface that expresses the following idea: "classes implementing this interface must have a void function named update, with a fixed but indeterminate number of parameters of the same (template parameter) type."  In other words, some implementing classes will have void update(T a), some void update(T a, T b), etc.  Admittedly, this kind of defeats the purpose of an interface, but I thought I would try to hack around it anyhow.  :)
>
> Option 1: put lots of update() functions in the interface, one with each possible number of parameters; implement every one in every derived class; and spew some static asserts if you try to use the wrong ones.  Yuck.
>
> Option 2: variadic functions: declare void update(T[] params ...) in the interface, and try to specialize to a fixed number of parameters in implementing classes.  D doesn't want to let me do this literally, and params.length nor _arguments.length are static constants -- though it seems like they could be.  I want to catch calls with the wrong number of arguments at compile time.
>
> Option 3: variadic templates: declare void update(P...)(P args) in the interface, and then define what you like in implementing classes.  This works, but too well: there doesn't seem to be any way to constrain the type of the arguments, which I would like the interface to do.
>
> Other options?  Is there a way to do this?

No, not really.  The entire purpose of putting a function in an
interface is so that anything that implements it conforms to it
exactly, so you can call the method on any interface reference.  How
the heck would you call .update() on an interface reference if you
didn't know, at compile time, how many params the derived class's
update method took?

This sounds more like a job for duck typing, but I don't know what you're doing.


More information about the Digitalmars-d-learn mailing list