accessing numeric template parameters
Philippe Sigaud via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Nov 3 13:16:58 PST 2014
On Mon, Nov 3, 2014 at 3:27 PM, Dominikus Dittes Scherkl via
Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> wrote:
> If I have a struct with numeric template parameter, how can I access it
> within member functions? Like normal member variables? And how about the
> constructor?
>
> struct polynomial(uint base)
> {
> private:
> uint[] N;
> public:
> this(uint x) { base = x; }
base is part of the type. polynomial is just a 'recipe' for a type,
the real struct would be Polynomial!(0), Polynomial!(1), etc. Note
that Polynomial!0, Polynomial!1, ... are all different types.
Being part of the type means it's defined only at compile-time, you
cannot use a runtime value (like 'x') to initialize it.
Note that with your current code, `base' is not visible outside
Polynomial. You can alias it to a field to make it visible:
struct Polynomial(uint base)
{
alias b = base; // b is visible outside (but set at compile-time !)
...
}
You can create one like this:
Polynomial!2 poly;
poly.N = [0,1,0,0,1,1];
assert(poly.b == 2);
Of course, you cannot change b: `poly.b = 3;' is forbidden.
More information about the Digitalmars-d-learn
mailing list