Why does the following throw a compiler error:

class A
{
public:
    int f() const
    {
        return 5;
    }

protected:
    invariant()
    {
        assert (f() == 5);
    }
}

main.d(14): Error: cannot call public/export function f from invariant.

I understand the concept of invariant; you want to check the state of the class between every public call to a method.

However, immutable or const member functions cannot alter the state of the class (unless this was passed?), so invariant checks surrounding those functions are redundant. The invariant call could be left aside and no infinite loop would appear, casting the compiler error wrong.


I came to this since I create hierarchies with objects, which define:

bool hasParent() const
{
    return (parent !is null);
}

using this little function is easier within the class, but possibly outside too. But defining it public defies invariant().

有帮助吗?

解决方案

It's most likely an omission. Feel free to file an enhancement request on Bugzilla.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top