C++ Logo

std-proposals

Advanced search

Low-hanging fruit: virtual plain-old-data members

From: denis bider <denisbider.ietf_at_[hidden]>
Date: Mon, 14 Oct 2019 14:23:10 -0500
Example of problem:

struct GenericService {
    virtual bool DoOtherThing() const = 0;

    void DoComplexThing() {
        ...
        bool doOtherThing = DoOtherThing();
        if (doOtherThing) { ... }
        ...
    }
};

struct SpecificService : GenericService {
    bool DoOtherThingToo() const override final { return true; }
};

Issues:

- It's a violation of the zero-overhead rule that I have to call a virtual
function just to get a polymorphic constant.

- No formal way to specify if DoOtherThing() should always return the same
value.

Proposed solution:

struct GenericService {
    virtual bool const vc_doOtherThing = 0;

    void DoComplexThing() {
        ...
        if (vc_doOtherThing) { ... }
        ...
    }
}

struct SpecificService : GenericService {
    bool const vc_doOtherThing override final { true };
};

Instead of storing a function pointer in the virtual table, and then
calling the function pointer to get a value; it should be possible to just
store the value in the virtual table.

This should work for plain-old-data types with trivial construction and
destruction. There's no desperate need to support virtual std::string
members or std::vectors, which would involve significant complications.
Storing plain-old-data types is not complex, though.

denis

Received on 2019-10-14 14:25:35