Cross platform C++ code architecture

前端 未结 8 617
广开言路
广开言路 2021-01-31 00:18

I\'m having a bit of a go at developing a platform abstraction library for an application I\'m writing, and struggling to come up with a neat way of separating my platform indep

8条回答
  •  故里飘歌
    2021-01-31 00:42

    So... you don't want to simply use Qt? For real work using C++, I'd very highly recommend it. It's an absolutely excellent cross-platform toolkit. I just wrote a few plugins to get it working on the Kindle, and now the Palm Pre. Qt makes everything easy and fun. Downright rejuvenating, even. Well, until your first encounter with QModelIndex, but they've supposedly realized they over-engineered it and they're replacing it ;)

    As an academic exercise though, this is an interesting problem. As a wheel re-inventor myself, I've even done it a few times now. :)

    Short answer: I'd go with PIMPL. (Qt sources have examples a-plenty)

    I've used base classes and platform specific derived classes in the past, but it usually ends up a bit messier than I had in mind. I've also done part of an implementation using some degree of function pointers for platform specific bits, and I was even less happy with that.

    Both times I ended up with a very strong feeling that I was over-architecting and had lost my way.

    I found using private implementation classes (PIMPL) with different platforms specific bits in different files easiest to write AND debug. However... don't be too afraid of an #ifdef or two, if it's just a few lines and very clear what's going on. I hate cluttered or nested #ifdef logic, but one or two here and there can really help avoid code duplication.

    With PIMPL, you're not constantly refactoring your design as you discover new bits that require different implementations between platforms. That way be dragons.

    At the implementation level, hidden from the application... there's nothing wrong with a few platform specific derived classes either. If two platform implementations are fairly well defined and share almost no data members, they'd be a good candidate for that. Just do it after realizing that, not before out of some idea that everything needs to fit your selected pattern.

    If anything, the biggest gripe I have about coding today is how easily people seem to get lost in idealism. PIMPL is a pattern, having platform specific derived classes is another pattern. Using function pointers is a pattern. There's nothing that says they're mutually exclusive.

    However, as a general guideline... start with PIMPL.

提交回复
热议问题