views:

308

answers:

8

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?"

+12  A: 

To actually implement cross platform functionality that requires OS support, (like sockets) you're going to have to write code that simply won't compile on certain platforms. That means your object-oriented design will need to be supplemented with preprocessor directives.

But since you'll have to use the preprocessor anyway, it's questionable whether something like a win32socket (for example) which inherits from a socket base class is even necessary or useful. OO is generally useful when different functions will be polymorphically selected at runtime. But cross-platform functionality is usually more of a compile-time issue. (e.g. there's no use in polymorphically calling win32socket::connect if that function doesn't even compile on Linux!) Therefore, it might be better to simply create a socket class which is implemented differently depending on the platform using preprocessor directives.

Charles Salvia
It's not really necessary to litter your code with preprocessor conditionals - just put platform-specific code into separate files and do the selection in makefiles/build scripts.
Nikolai N Fetissov
Right; the preprocessor directives can be something as simple as including different header files depending on the platform.
Charles Salvia
Absolutely - my question was more about how one should go about creating the different implementations for a generic socket class. Apologies for the ambiguity there.
ShZ
@ShZ, I understand that but what I'm saying is that virtual functions, and OO in general, is a run-time mechanism and therefore not really useful or necessary for the purposes of designing cross platform code.
Charles Salvia
+1  A: 

The second approach is better because it allows you to create member functions that will exist only on one of the platforms. Then, you can use the abstract class in the platform-independentcode, and the concrete class in the platform-specific code.

Example:

class Foo
{
    public:
        virtual ~Foo() {};
        virtual void Bar() = 0;
};   
class Win32Foo : public Foo
{
    public:
        void Bar();
        void CloseWindow(); // Win32-specific function
};

class Abc
{
    public:
        virtual ~Abc() {};
        virtual void Xyz() = 0;
};   
class Win32Abc : public Abc
{
    public:
        void Xyz()
        {
           // do something
           // and Close the window
           Win32Foo foo;
           foo.CloseWindow();
        }
};
Igor Oks
+1  A: 

Ideally you would concentrate the differences at the lowest level possible.
So your top level code calls Foo() and only Foo() needs to care internally what OS it is calling.

ps. Take a look at 'boost' it contains a lot of stuff to handle cross platform network filesystems etc

Martin Beckett
+7  A: 

Define your interface, which forwards to detail calls:

#include "detail/foo.hpp"

struct foo
{
    void some_thing(void)
    {
        detail::some_thing();
    }
}

Where "detail/foo.hpp" is something like:

namespace detail
{
    void some_thing(void);
}

You'd then implement this in detail/win32/foo.cpp or detail/posix/foo.cpp, and depending on which platform your compiling for, compile one or the other.

Common interface just forwards calls to implementation-specific implementations. This is similar to how boost does it. You'll want to look at boost to get the full details.

GMan
That's a good idea, and I'll definitely take a look at what Boost does there.I'm curious though, does this pattern allow class state to vary between implementations? For example, Posix vs Win32 file handles have a different type - if I were writing a file wrapper, the state structs/classes would have to be different.
ShZ
You'd make a `file_handle` class, and just stuff the handle into a `void*`, usually. The implementation can cast it back to what it needs. This is guaranteed safe by the standard. This method also works well if you dynamically load implementations, as you just replace `detail::whatever` with `some_function_pointer`, loaded from the library.
GMan
+1: always delegate to the build system what is build-time specific
Steve Schnepp
+1  A: 

Delegating as in your first example or GMan's works pretty well, especially if the platform-specific part will need many platform-specific members (e.g. members of types that only exist in one platform). Downside is you have to maintain two classes.

If the class is going to be simpler, without a lot of platform specific members, you can just use a common class declaration, and write two implementations in two different .cc files (plus maybe a third .cc for platform independent method implementations). You may need some #ifdefs in the header file for the few platform-specific members or members with platform-specific types. This way is more of a hack, but can be easier to start with. You can always switch to delegates if it gets out of control.

Reed Hedges
+3  A: 

You don't need to go OOP in order to be cross platform. Cross platform is more of an architecture and design paradigm.

I suggest isolating all the platform specific code from the standard code, such as sockets GUI. Compare these across the different platforms and write a layer or wrapper that is generic. Use this layer in your code. Create library functions to implement the platform specific implementation of the generic layer.

The platform specific functions should be in separate libraries or files. Your build process should use the correct libraries for the specific platforms. There should be no changes to your "standard" code.

Thomas Matthews
A: 

As others have noted, inheritance is a wrong tool for the job. The decision of the concrete type to use in your case is made at build time, and the classic polymorphism enables that decision to be made at run-time (i.e. as a result of users' action).

Nemanja Trifunovic
A: 

You can use template specialization to separate code for different platforms.

enum platform {mac, lin, w32};

template<platform p = mac>
struct MyClass
{
 // Platform dependent stuff for whatever platform you want to build for default here...
};

template<>
struct MyClass<lin>
{
 // Platform dependent stuff for Linux...
};

template<>
struct MyClass<w32>
{
 // Platform dependent stuff for Win32...
};

int main (void)
{
 MyClass<> formac;
 MyClass<lin> forlin
 MyClass<w32> forw32;
 return 0;
}