如何在两个不同的命名空间(但只写一次)中使用相同的标头定义,命名空间有不同的实现?
How to have same header definition in two different namespaces (but written once), with different implementations for namespaces?
假设我的程序由两个受信任和不受信任的组件组成。我想只需要在两个不同的命名空间中对类 A 的声明进行一次编码,但它们的实现可以根据命名空间而有所不同,只需对通用 API 进行一次编码。我不想将宏用于#ifdef UNTRSUTED
.etc等实现。
我不想使用抽象和继承来实现不同的行为。我只是好奇这是否可能。
在标题 A.h 中,我将有
// A.h
#pragma once
namespace app {
// I know I can't get what I want with naming the same namespace twice
namespace untrusted, trusted {
class A {
doDifferentFoo();
doCommonBar() // this one is common between two impls;
}
}
}
在实现中,我将拥有 A-common.cpp(只为两个命名空间实现一次公共接口(、A-untrusted.cpp(为不受信任的命名空间实现 doDifferentFoo(和 A-trusted.cpp(为受信任的命名空间实现 doDifferentFoo(
我想最简单的方法是将公共声明移动到一个额外的文件中,然后包含它两次:
A_detail.h:
// No `#pragma once` here!
class A {
doDifferentFoo();
doCommonBar(); // this one is common between two impls;
};
啊:
#pragma once
namespace app {
namespace trusted {
#include "a_detail.h"
}
namespace untrusted {
#include "a_detail.h"
}
}
A-不受信任.cpp:
#include "a.h"
namespace app { namespace untrusted {
// ...
} }
A-信任.cpp:
#include "a.h"
namespace app { namespace trusted {
// ...
} }
A-common_detail.cpp(可以选择不同的文件结尾;不应该编译为翻译单元(:
// common definitions/declarations without `namespace`
A-常见.cpp:
namespace app {
namespace untrusted {
#include "A-common_detail.cpp"
}
namespace trusted {
#include "A-common_detail.cpp"
}
}
我不确定这是否值得。或者,您可以(在每个具有通用代码的文件中(对所有通用代码使用宏,并为两个命名空间调用两次。但是,您确实说过您不想使用宏。
如果没有预处理器的帮助,就无法做到这一点,因为每个声明(只有一个声明符(在一个作用域中只声明一个名称。
//A.h
class A {
void doDifferentFoo();
void doCommonBar()
{ // ...
}
};
A_trusted.h
namespace app
{
namespace trusted
{
#include "A.h"
void A::doDifferentFoo() // can be moved to cpp-file if needed/wanted
{
}
}
}
A_untrusted.h
namespace app
{
namespace untrusted
{
#include "A.h"
void A::doDifferentFoo() // can be moved to cpp-file if needed/wanted
{
}
}
}
相关文章:
- 在命名空间中定义函数还是限定函数
- 使用命名空间时出现多个定义错误
- 如何对命名空间限定类型进行类型定义?
- C++未定义的命名空间
- 命名空间更改函数定义
- 使用命名空间在另一个".cpp"文件中定义
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- 在方法定义中显式指定命名空间
- 在命名空间中定义变量
- 如何为缺少预定义运算符而不扩展命名空间"std"的标准类型定义运算符>> (istream &, ...)?
- 如何理解c++中在命名空间内部定义的枚举类型enum
- 在 c++ 中使用类的命名空间定义类的成员
- cgo调用C++中定义的函数(位于命名空间中)
- 在内联命名空间中扩展最初在内联命名空间的封闭命名空间中定义的命名空间
- 将以"_[a-z0-9]"开头和"using"的标识符导入全局命名空间是否定义良
- 自定义提升前缀/命名空间 - 如何使用
- C++最佳实践 - 在多个命名空间中定义类
- 共享库中使用"使用命名空间"定义的符号错误
- C++:在'#include <files>'之前是否允许命名空间定义。
- 命名空间定义和异常