【发布时间】:2018-05-26 16:18:57
【问题描述】:
以下代码出现此错误
嵌套名称说明符中使用的不完整类型“Foo::Pimpl”
另一个Foo.hpp
struct AnotherFoo {
void methodAnotherFoo(Foo &);
};
另一个Foo.cpp
#include "Foo.hpp"
#include "AnotherFoo.hpp"
void AnotherFoo::methodAnotherFoo(Foo &foo) {
// here i want to save the function pointer of methodPimpl(), std::function for ex:
std::function<void(void)> fn = std::bind(&Foo::Pimpl::methodPimpl, foo._pimpl); // <-- Here i am getting the error
}
Foo.hpp
struct Foo {
Foo();
class Pimpl;
std::shared_ptr<Pimpl> _pimpl;
};
Foo.cpp
#include "Foo.hpp"
struct Foo::Pimpl {
void methodPimpl(void) {}
};
Foo::Foo() : _pimpl(new Pimpl) {}
main.cpp
#include "Foo.hpp"
#include "AnotherFoo.hpp"
int main() {
Foo foo;
AnotherFoo anotherFoo;
anotherFoo.methodAnotherFoo(foo);
}
谁有解决这个问题的好办法?
我要实现的主要目标是使 methodAnotherFoo 方法的签名从头文件中隐藏。
【问题讨论】:
-
@Slava Actually you can.
-
我认为
PIMPL不太可能需要std::shared_ptr,std::unique_ptr不是更合适吗? -
作为 PImpl 模式的替代方案,您可以使用抽象基类、工厂函数(可能作为类静态函数,它将返回 std::unique_ptr
)和包含所有细节的“impl”派生类。缺点是 vtable 查找的额外间接性,但由于 pimpl,您基本上具有相同的成本。
标签: c++ c++11 c++-standard-library pimpl-idiom