Re: Using templates to wrap OS APIs
* Scott Meyers:
Wrapping platform-dependent APIs has got to be a common C++ activity, and
it seems like templates should be well-suited to the job. Yet I keep
coming back to ifdefs. Can somebody please point out the error of my
ways?
The general problem is that in order to use a platform-dependent API you
need
its declarations, which are provided via a header, and including that header
isn't in general practical (or even possible) on other platforms.
The general C++ solution is separate compilation, including the relevant
headers
only in the relevant implementation files. This is called a "compilation
firewall". It can be generalized up (which is useful in Java but in C++
often
just needless complication and inefficiency) as separate compilation of a
shared
library which is then accessed via some kind of singleton/factory. Another
generalization which is more useful in C++ is the PIMPL idiom. Which itself
has
a number of variants and generalizations.
Given separate compilation you can then select the platform's relevant
file(s)
by using preprocessor directives and/or higher level platform specific
selection
of files (i.e. different packages for different platforms. The latter is
generally preferable since the user's selection of platform is only done
once.
Cheers & hth.,
- Alf
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]