Defining a function once that appears in multiple name spaces

雨燕双飞 提交于 2019-12-11 05:07:32

问题


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?


回答1:


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.




回答2:


I guess you want static polymorphism - means a template or a macro:

Template:

#include "C_Functions.h"
#include "Asm_Functions.h"
#include "LibX_Functions.h"

enum Namespace 
{
    NamespaceC,
    NamespaceAsm,
    NamespaceLibX
}

template <Namespace> Func();
template <> inline Func<NamespaceC>() { return C_Func(); }
template <> inline Func<NamespaceAsm>() { return Asm_Func(); }
template <> inline Func<NamespaceLibX>() { return LibX_Func(); }

const Namespace NSpace = ...
inline void f() {
    Func<NSpace>()
}

An advantage is: You may have a common implementation for a specific function. Similar you may do with macros (or you combine it) I fear it ends up in #ifdef ... anyway, unless you try to have one lib for any hardware/system (which is pointless, in my view).



来源:https://stackoverflow.com/questions/18146206/defining-a-function-once-that-appears-in-multiple-name-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!