Pure constructors in class templates

70 views Asked by At

I have some code that works, and I'm not sure why. I'm instantiating a class as an immutable variable. There are no immutable constructors in the class and none are labeled as pure, but it just works anyway.

I also read that pure constructors can be used across the board for mutable, immutable, const, and shared instances

The only thing I can find on the D website is that purity is inferred in function templates. Should I assume that since my class is parameterized (or a class template) that the compiler is inferring the purity of all the methods, including the constructor?

Code below:

public class Data(size_t numInputs, size_t numTargets)
{
  ...
  public this(in double[][] data, in bool[] filter, in bool doNorm = true)
  {
    ...
  }
}
1

There are 1 answers

0
Adam D. Ruppe On BEST ANSWER

The only thing I can find on the D website is that purity is inferred in function templates. Should I assume that since my class is parameterized (or a class template) that the compiler is inferring the purity of all the methods, including the constructor?

Yes. Since the class is a template, all the methods are also templates (consider that they have to be since the hidden this parameter's type comes from the template). Thus, their body must be available in the source. The two requirements for inferred attributes are body source available and a template parameter for them (and also the function must not try to call or inspect itself, but you don't do that either) thus it can be inferred as pure.