Same:)
class _object { }; class WindowsObject : public _object { }; class LinuxObject public _object { }; #if defined(WIN32) typedef WindowsObject Object; #else typedef LinuxObject Object; #endif Object myObject;
EDIT: Naturally, the interface that WindowsObject and LinuxObject expose must be the same. In this example, _object will be the abstract base class that defined the interface, and LinuxObject and WindowsObject then implement this interface, hiding platform-specific things in their implementation files.
Example
_object.h
class _object { public: virtual void doSomething() = 0; };
WindowsObject.h
#include "_object.h" class WindowsObject : public _object { public: virtual void doSomething(); };
WindowsObject.cpp
#if defined(WIN32) #include <windows.h> void WindowsObject::doSomething() { // do something totally reliant on windows here }; // eo doSomething #endif
Then you will do the same for LinuxObject.h and LinuxObject.cpp , with the latter having completely different preprocessor instructions. for example, #if defined(UNIX) or some such flavor. Pay attention to WIN32 safeguards around the implementation. Then you will have the main header file that you use:
#if defined(WIN32) #include "WindowsObject.h" typedef WindowsObject Object; #else #include "LinuxObject.h" typedef LinuxObject Object; #endif
Now in your program
Object a; a.doSomething();
It is worth noting that if this is just an odd line of code that differs in your complex object (for example, initialization call during initialization, destruction), you might be better off with one object-agnostic object and put the defenders in the implementation.This solution makes more sense. when there are huge differences.
source share