using templates as substitutions for #ifdef

From: Chris Goller (goller_at_gmail.com)
Date: 03/08/05


Date: 8 Mar 2005 11:08:34 -0800

Imagine a cross platform library. A particular object wraps up
operating system specific functionality and presents it in a uniform
manner.

Generally, people use ifdefs to change the functionality of a
particular piece of code to match that of the native operating system
(#ifdef _WINDOWS, etc)

I'm wondering if it is possible to use templates to accomplish this
same functionality.

Basically, there might be something like:

enum os_type
{
        LINUX,
        SOLARIS,
        WINDOWS
};

template <os_type os>
class os_wrapper
{
        void os_specific_function();
};

template<>
class os_wrapper<WINDOWS>
{
        void os_specific_function()
        {
                windows_specific_function();
        }
};

template<>
class os_wrapper<SOLARIS>
{
        void os_specific_function()
        {
                solaris_specific_function();
        }

};

This way the compiler wouldn't need to compile the class unless it was
instantiated with an operating system as a template argument.

However, the code above doesn't seem to work at least in g++.

So, my question is it possible with some template kung fu to wrap OS
specific functions so that the compiler will compile them ONLY if they
have been instantiated and ignore the code otherwise?

Chris



Relevant Pages

  • Re: using templates as substitutions for #ifdef
    ... A particular object wraps up ... > operating system specific functionality and presents it in a uniform ... > particular piece of code to match that of the native operating system ... > This way the compiler wouldn't need to compile the class unless it was ...
    (comp.lang.cpp)
  • Re: Enable/Disable Toolbar button
    ... Changing the state of a toolbar button effectively makes the global template ... and I can slip the 'proper' functionality in under one of them. ... the WindowSelectionChange event won't fire. ... Private Sub Document_Open ...
    (microsoft.public.word.vba.general)
  • Re: Enable/Disable Toolbar button
    ... On dirtying the template: ... and I can slip the 'proper' functionality in under one of them. ... You may have several buttons with the same .ID and .Tag ... Private Sub Document_Open ...
    (microsoft.public.word.vba.general)
  • Re: Visio 2003 Template Problem
    ... used to open up with a "drawing" that I could use and manipulate. ... Do you have any idea how I can get the drawing functionality back instead of ... the only purpose of a template but they can just provide a blank ... Now I did a 3rd install and damn the same blank template. ...
    (microsoft.public.visio.general)
  • Re: Keyboard
    ... cents worth of disk space. ... With almost no exceptions, every new version of any operating system, ... that extra functionality takes more ... Microsoft MVP - Windows Desktop Experience ...
    (microsoft.public.windowsxp.help_and_support)