Of course, I know the best answer is "don't write your own cross-platform code, someone has already done what you need," but I'm doing this as a hobby/learning exercise and not in any paid capacity. Basically, I'm writing a smallish console application in C++, and I'd like to make it cross platform, dealing with things like files, sockets, and threads. OOP seems like a great way to handle this, but I haven't really found a good pattern for writing classes that share the same interface cross platform.
The easy approach is to just plan out some meta-interface, use that throughout the rest of the program, and just compile the same class with different files depending on the platform, but I feel like there's got to be a better way that's more elegant; at the very least, something that doesn't confuse IntelliSense and its ilk would be nice.
I've taken a look at some of the smaller classes in the wxWidgets source, and they use an approach that uses a private member holding data for the class, e.g
class Foo
{
public:
Foo();
void Bar();
private:
FooData data;
};
You can then compile this by simply choosing different implementation files depending on the platform. This approach seems pretty clunky to me.
Another approach I've considered is writing an interface, and swapping out classes that inherit from that interface depending on the platform. Something like this:
class Foo
{
public:
virtual ~Foo() {};
virtual void Bar() = 0;
};
class Win32Foo
{
public:
Win32Foo();
~Win32Foo();
void Bar();
};
Of course this kind of screws up the actual instantiation since you don't know which implementation to create an object of, but that can be worked around by using a function
Foo* CreateFoo();
and varying the implementation of the function based on which platform you're running on. I'm not a huge fan of this either, because it still seems clunky littering the code with a bunch of instantiation method (and this would also be inconsistent with the method of creating non-cross-platform objects).
Which of these two approaches is better? Is there a better way?
Edit: To clarify, my question is not "How do you write cross-platform C++?" Rather, it's "What is the best method to abstract away cross-platform code using classes in C++, while retaining as much benefit from the type system as possible?"