0

I'm trying to create a C++ class hierarchy of UI "view" classes that wrap platform-specific UI classes. My classes use the pimpl idiom to hide the implementation from the header file. The Impl structs contain another pointer, to classes in the platform hierarchy.

(I used "PS" to abbreviate "platform specific".)

In the code below, I try to show a boiled down example of the base class (View), and one derived class (Button), along with the classes that they wrap. There is a static cast in the Button's implementation. All of the subclasses of View will have a lot of these casts. Is there way define the Impl struct so that the compiler understands the types better here, so I don't need to use the static casts?

// In .hh file

class View {
public:
    virtual ~View() = default;
    ...
protected:
    struct Impl;
    Impl *impl;
    View();
    View(Impl *impl);
};

class Button: public View {
public:
    Button();
    void setText(const string &text);
};

// In .cc file 

View::View() :impl(nullptr) {}
View::View(Impl *impl) :impl(impl) {}

struct View::Impl {
    PSView *psView;
};

void View::doStuff() {
    ... impl->psView ... // fine, no cast needed here 
}

Button::Button() {
    PSButton *b = new PSButton();
    impl = new Impl{b};
}

void Button::setText(const string &text) {
    PSButton *myImpl = static_cast<PSButton*>(impl->psView);
    myImpl->setTitle(text);
}

In my real code, it's a bit weirder, because the platform specific types are Apple's Objective-C classes. I'm putting that aside for now to try and clean up and simplify this question.

Rob N
  • 15,024
  • 17
  • 92
  • 165
  • 1
    Insufficient information, and what's there is either confusing or misleading (or both). To work out a way to remove `static_cast(impl-nsview)` it is necessary to have information about the relationship - if any - between types `NSView` and `NSStackView` - and you have provided no information about either other than that `NsView` is "platform specific, hidden from header file". Mixing two languages doesn't help. – Peter Aug 25 '22 at 02:14
  • Actually, I said `NSStackView` is a subclass of `NSView`, but I said it in the code comment. Maybe I should move that up to the text to make it more obvious. – Rob N Aug 25 '22 at 02:42
  • I've edited the question to try to improve it. Sorry about that. It was sloppy and I probably shouldn't post questions when I'm tired at the end of the day. – Rob N Aug 25 '22 at 04:59
  • This sort of question comes up frequently, and there are essentially no good answers, other than using templated code (which brings its own limitations). – Sneftel Aug 25 '22 at 08:34
  • @Sneftel Okay. Yes, I was hoping there was a solution lurking in the dark areas of C++ that I don't yet know - the template stuff. – Rob N Aug 25 '22 at 13:17

0 Answers0