无法以shared_from_this的继承进行编译
Unable to compile with inheritance of shared_from_this
我正在使用自制的shared_from_this类(CEnableSharedFromThis),因为我在C++03以下,我不能在我的项目中使用boost。
我有一个A类,看起来像这样:
class A : virtual CEnableSharedFromThis<A>
{
...
}
和B类这样的:
class B : public A, virtual CEnableSharedFromThis<A>
{
void foo()
{
Poco::SharedPtr<B> b(sharedFromthis());
}
}
我看到有些人对模棱两可的方法有错误。所以我使用虚拟继承,我没有这个错误。
但是我有一个新的,我不能放弃 foo() 方法。
编译器说:
错误:无法从基本
CEnableSharedFromThis<A>
转换为派生 通过虚拟底座CEnableSharedFromThis<A>
键入A
所以我尝试以下 foo() 方法:
void foo()
{
Poco::SharedPtr<B> b(B::sharedFromthis());
}
但它什么也改变不了。
知道吗?
编辑:
根据您的建议,我删除了 B 的 CEnableSharedFromThis 的继承,并像这样更改 foo() 函数:
class B : public A
{
void foo()
{
Poco::SharedPtr<B> b(sharedFromthis().cast<B>());
}
}
覆盖它并改用static_pointer_cast。
class B : public A
{
Poco::SharedPtr<B> sharedFromThis() {
return Poco::StaticPointerCast<B>(CEnableSharedFromThis<A>::sharedFromThis());
}
void foo()
{
Poco::SharedPtr<B> b(sharedFromthis());
}
}
这是假设存在与std::static_pointer_cast
类似的Poco::StaticPointerCast
。
相关文章:
- C++ 多级虚拟继承编译问题
- 编译时继承类中的隐式虚拟与显式虚拟
- 在编译时检查未实例化的类模板是否继承自其第一个模板参数
- 继承的构造函数,在 clang++3.9 中编译,在 g++ 7 中失败
- 使用多重继承时出现编译错误
- 为什么下面的代码不会编译(c++中的继承)
- 继承可以用来减少C++中编译代码的大小吗?
- C++ 上的循环依赖和继承编译错误
- 编译器无法编译继承 C++
- 如果对象是堆栈创建的(包括继承的类型),是否可以发出编译错误
- 获取多重继承中基类的编译时常量偏移量
- 可以用参数包编译C 17 lambda继承的编译器
- 为什么 Visual C++无法编译从私有嵌套类继承的友元模板
- C++中的继承和模板:为什么以下一段代码不编译?
- 继承结构的类型转换导致g++编译错误
- 继承受保护的函数和公共变量C++时发生多重继承编译错误
- 钻石继承方案在 G++ 中编译良好,但在 VC++/Eclipse 中产生警告/错误
- C++的多重继承和多重实现编译但崩溃
- 继承编译时或运行时
- 多重(菱形)继承编译而不"virtual",但不使用