I have heard that a way to write Cross Platform c++ code is to define classes as follows (for example, a Window class):
window.h
window_win32.cpp
window_linux.cp
There is more ways to solve this problem - each has it's pros and cons.
1.) Use macros #ifdef, #endif
// Note: not sure if "WINDOWS" or "WIN32" or something else is defined on Windows
#ifdef WINDOWS
#include
#else
// etc.
#endif
class MyClass
{
public:
// Public interface...
private:
#ifdef WINDOWS
HWND m_myHandle;
#else
// etc.
#endif
};
Pros:
Cons:
2.) As was there already written, you might use polymorphism:
// IMyClass.h for user of your class:
class IMyClass
{
public:
virtual ~IMyClass() {}
virtual void doSomething() = 0;
};
// MyClassWindows.h is implementation for one platform
#include
#include "IMyClass.h"
class MyClassWindows : public IMyClass
{
public:
MyClassWindows();
virtual void doSomething();
private:
HWND m_myHandle;
};
// MyClassWindows.cpp implements methods for MyClassWindows
Pros:
Cons:
3.) PIMPL idiom.
// MyClass.h
class MyClass
{
public:
MyClass();
void doSomething();
private:
struct MyClassImplementation;
MyClassImplementation *m_impl;
}
// MyClassWindows.h
#include
#include "MyClass.h"
struct MyClassImplementation
{
HWND m_myHandle;
void doSomething();
}
In this case, MyClassImplementation keeps all needed (at least platform specific) data and implements what is needed (again, platform specific). In MyClass.cpp you include the platform specific implementation (methods can be inline), in constructor (or later if you want to - just be careful) you allocate the implementation and in destructor you will destroy it.
Pros:
Cons:
4.) Define a neutral type, which is big enough to keep your data. For example long long int.
// MyClass.h
class MyClass
{
public:
MyClass();
void doSomething();
private:
typedef unsigned long long int MyData;
MyData m_data;
};
In implementation (e.g. MyClassWindows.cpp) you always need to cast (reinterpret casting) between MyClass::MyData and actual data stored.
Pros:
Cons:
So use the one which is best fitting to your problem... and your personality :3 because with today's power are all four more or less relatively equal in terms of speed and space.