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

Doctor J nobody at nowhere.com
Fri Jul 3 11:54:12 PDT 2009


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?




More information about the Digitalmars-d-learn mailing list