On Monday, 14 September 2020 at 18:58:44 UTC, 60rntogo wrote:
On Monday, 14 September 2020 at 17:11:59 UTC, k2aj wrote:
AFAIK the only way to have default ref arguments is to use a global variable:
---
extern(C++) struct Foo
{
  int x;
}
immutable foo1 = Foo(1);
extern(C++) void fun(const ref Foo foo = foo1);
---

Thanks. This appears to work, but feels like a hack. I can live with that, but I'm still wondering if there is a more idiomatic way of solving the problem.

D doesn't let rvalues bind to const ref (well, `in` will do that, but it's D-only). What was described as "global variable", is more of a "manifest constant lvalue". A (static) immutable variable with an initializer will always be CTFE-d and available at compile time, so in this case it is *exactly* what you need.

Also note that a default parameter doesn't affect the mangling / ABI, because it works exclusively on the caller side. Thus, you could just remove the default argument and your `extern(C++)` binding would work just fine. But if you want to provide the same API, `[static] immutable` + initializer is the way to go.

Reply via email to