定义一个出现在多个名称空间中的函数
我正在尝试为一组函数和类定义一个通用接口,这些函数和类将具有多个不同的后端实现(使用不同的库).
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();
现在,我想对该功能进行3个单独的实现.一个将是一个直线C,一个将是一个手工编码的汇编器,一个将使用库'x'.
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();
}
是否有避免这种情况的好模式?当有100个奇数函数时,它将变得更加痛苦.
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?
使其成为抽象基类中的虚函数.随时在派生类中实现它.
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{ ... }
}
等