Domanda

I have a class method with a bool template-parameter (is_const) which only calls a mutable function when is_const is false (using static if). How can I tell the D compiler to make this function const for is_const = true but not for is_const=false? I don't want to have to copy-paste the function, but I can't see any other way to do it. (I can't use inout because it does indeed behave differently for is_const=false and is_const=true)

È stato utile?

Soluzione

You can add a const overload that forwards to the de facto const implementation:

class C
{
    void m(bool is_const)() // de-facto const when is_const is true
    {
        static if(!is_const) {/* ... mutate ... */};
    }
    void m(bool is_const)() const if(is_const)
    {
        return (cast() this).m!true();
    }
}

You then have to be extra careful not to mutate when is_const is set.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top