如何在两个不同的命名空间(但只写一次)中使用相同的标头定义,命名空间有不同的实现?

How to have same header definition in two different namespaces (but written once), with different implementations for namespaces?

本文关键字:命名空间 定义 实现 两个 一次      更新时间:2023-10-16

假设我的程序由两个受信任不受信任的组件组成。我想只需要在两个不同的命名空间中对类 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
{
}
}        
}