Make interchangeable class types via pointer casting only, without having to allocate any new objects?

前端 未结 4 1156
半阙折子戏
半阙折子戏 2020-12-17 04:24

UPDATE: I do appreciate \"don\'t want that, want this instead\" suggestions. They are useful, especially when provided in context of the motivating scenari

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-17 05:05

    The term Accessor is a dead giveaway: what you are looking for is a Proxy.

    There is no reason for a Proxy not to be passed around by value.

    // Let us imagine that NodeBase is now called Node, since there is no inheritance
    
    class AccessorFoo {
    public:
        AccessorFoo(Node& n): node(n) {}
    
        int bar() const { return node->bar; }
    
    private:
        std::reference_wrapper node;
    };
    

    And then you can freely convert from one accessor to another... though this smells. Normally the very goal of having an accessor is to restrict access in a way, so casting nilly willy to another accessor is bad. However one could support casting to a narrower accessor.

提交回复
热议问题