Class parameters that are either setable at run-time or compile-time
Markus Mayr via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Aug 10 03:47:33 PDT 2014
Hello,
I am new to D. I am sorry if this question was already answered
or if it is trivial. I am having a class. That class takes
several parameters that may be known at either compile time or
run time. I want users of my class to be able to pass the
parameters either as template parameters to the class or to the
constructor of that class. At the moment, I have got the
following code:
class X(int a = some_dummy_value, int b = some_dummy_value)
{
static if (a == some_dummy_value) static immutable int a_
= a;
else immutable int a_;
// etc.
this(int a = some_dummy_value, int b = some_dummy_value) {
static if (a != some_dummy_value) this.a_ = a;
static if (b != some_dummy_value) this.b_ = b;
}
};
This works, as far as I can tell. But there is one problem: users
may forget to provide the value at compile time and run time. In
that case, the members a_, b_ end up with some_dummy_values. Of
course, I can notify the user at run time about this
misbehaviour, but I would prefer to tell them at compile time.
The only solution I am aware of is to use static if in order to
provide one of four constructors depending on the compile time
values of a, b, i.e.
* none provided at compile time,
* a provided at compile time,
* b provided at compile time,
* both provided at compile time.
This is perfectly fine for one or two arguments, but I have
gotten three of them (i.e. 8 constructors) and may want to add
more later on. Since the number of constructors scales
exponentially with the number of parameters, I have a feeling
that this approach won't scale well.
Is there any elegant solution to the problem?
By the way, this is why I am doing this: Depending on the values
of a and b, the class chooses how to implement some parts of its
interface; if a or b are not provided, it may choose generic but
slow fall back implementations. If there is any other solution to
that problem, I also would like to know.
Thanks a lot and I hope this is how this mailing list works!
Best regards,
Markus Mayr
More information about the Digitalmars-d-learn
mailing list