我正在将现有代码库迁移到 C++20 模块。在这个代码库中,我有一个带有成员方法的类,成员方法
module;
#include <memory>
export module A;
class A {
constexpr std::unique_ptr<A> generate(void); // constexpr is important here
};
有几个模块扩展A:
export module B;
class B: public A {
constexpr void configure(int i)
{ /* does something really important */ }
};
我想像这样实现 A::generate 。
constexpr std::unique_ptr<A> A::generate(int i)
{
if(i == 0) {
std::unique_ptr<B> b = std::make_unique<B>();
b.configure(/* do something */);
return b;
}
/* and so on */
}
请注意,我需要在
A::generate
中使用 B 的成员函数,因此我不能仅转发声明 class B;
并在模块 A 中执行此操作。
您建议我应该如何进行?
模块 A 接口 (a.ixx)
export module A;
export class A {
public:
constexpr std::unique_ptr<A> generate(int i);
};
模块A实现(a.cpp)
module A;
import B;
constexpr std::unique_ptr<A> A::generate(int i)
{
if (i == 0) {
std::unique_ptr<B> b = std::make_unique<B>();
b->configure(/* do something */);
return b;
}
// Handle other cases...
return nullptr;
}
模块 B 接口 (b.ixx)
export module B;
import A;
export class B : public A {
public:
constexpr void configure(int i);
};
模块B实现(b.cpp)
module B;
constexpr void B::configure(int i)
{
// Implement the configure method
}