Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const struct in D

I am trying to pass a struct as a compile time argument to a function. I think the code is self explanatory. I am fairly certain that this should work. But I don't know why it won't work.

void main(string[] args)
{
    const FooStruct fooStruct = FooStruct(5);

    barFunction!fooStruct();
}

public struct FooStruct()
{
    private const int value_;
    @property int value() { return value_; }

    this(int value) const
    {
        value_ = value;
    }
}

public static void barFunction(FooStruct fooStruct)
{
    fooStruct.value; /// do something with it.
}
like image 511
blipman17 Avatar asked Mar 19 '26 01:03

blipman17


1 Answers

public struct FooStruct()

Here, you're declaring FooStruct to be a templated struct, with no variables. If that's what you want, you'll need to refer to FooStruct!() on this line:

public static void barFunction(FooStruct fooStruct)

Since FooStruct takes no template arguments, there's not really any need for it to be templated, and you should probably declare it like this:

public struct FooStruct

When you do that, the error message changes to constructor FooStruct.this (int value) const is not callable using argument types (int). That's because you're invoking the mutable constructor. To fix that, change line 3 to read const FooStruct fooStruct =constFooStruct(5);.

Finally, when you call barFunction, you are attempting to pass fooStruct as a template parameter (barFunction!fooStruct()). Since barFunction is not a templated function, this fails. You probably meant barFunction(fooStruct).

like image 74
BioTronic Avatar answered Mar 21 '26 19:03

BioTronic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!