I have just discovered that the postblit constructor is not able to be invoked like a "normal" constructor, or, as one would manually do so in C++ with a copy constructor. Accordingly I have a couple questions:

1) What are the various ways to invoke the postblit constructor? I have not tested, but assume that:

auto s1 = MyStruct();
auto s2 = s1;

Is one such way to invoke it and that:

auto s1 = MyStruct;
foo(s1);

Where foo is defined as: void foo(MyStruct s) {}

is another way. Are there others?


2) I ran into this issue while attempting to leverage the postblit for code-reuse. In particular, I have a setup that is similar to:

struct A {
  this(B b) { /* Stuff */ }
}

struct B {

}

void foo(T)(T param) {
  auto a = A(param);
  /* Stuff */
}

unittest {
  foo(A()); //Fails
  foo(B()); //Succeeds
}

The notion being that A and B are 2 ways to represent the same thing, why not convert everything to the A format and proceed from there; I figured the compiler would optimize out the pointless copy when T == A. Alas, as shown in my unittest, foo fails to accept arguments of type A.

I suppose my question would be: What is the idiomatic way of accomplishing this form of code reuse in D?

I'd prefer to not have to write two versions of foo, even if one is as simple as converting the argument and passing it to the other. I'd also prefer to avoid having some shenangians along the lines of:

void foo(T)(T param) {
  static if (is(T == A)) {
    auto a = param;
  } else {
    auto a = A(param);
  }
}

As this would be difficult to express in a template constraint in the function signature.

Reply via email to