Search code examples
c++namespacesfunction-declaration

Defining a function once that appears in multiple name spaces


I am trying to define a common interface to a set of functions and classes that will have multiple different backend implementations (Using different libraries).

As such I'd really rather, simply, define a function in one place and not in each separate namespace.

For example, I have a global function:

extern void Func();

Now I want to have 3 separate implementations of that function. One would be a straight C, One would be a hand coded assembler and one would be using library 'x'.

I am effectively trying to avoid doing the following:

namespace C
{
     extern void Func();
}

namespace Asm
{
     extern void Func();
}

namespace LibX
{
     extern void Func();
}

Is there a good pattern to avoid doing this? When there are 100 odd functions it will become much more of a pain.

The only idea I can think of is to move all the definitions into a header file that has no header guards and then doing:

namespace C
{
     #include "Functions.h"
}

namespace Asm
{
     #include "Functions.h"
}

namespace LibX
{
     #include "Functions.h"
}

Is there a better way of doing this that anyone can think of?


Solution

  • Make it a virtual function in an abstract base class. Implement it whenever you feel like it in a derived class.

    class Foo{
    public:
        virtual void bar() const=0;
    }
    
    class FooASM:public Foo{
    public:
        virtual void bar() const{ ... }
    }
    

    etc.