gpt4 book ai didi

c++ - 使用类的 'this' 指针的 boost::intrusive_ptr 构造函数歧义

转载 作者:行者123 更新时间:2023-11-30 04:39:39 28 4
gpt4 key购买 nike

违规代码:

template<typename T>
class SharedObject {
public:
typedef boost::intrusive_ptr<T> Pointer;
typedef boost::intrusive_ptr<T const> ConstPointer;
inline Pointer GetPointer() {
return Pointer(this); //Ambiguous call here
}
inline ConstPointer GetPointer() const {
return ConstPointer(this);
}
...

并像这样使用:

template <typename T>
class SomeClass: public SharedObject<SomeClass<T> > {
public:
static inline boost::intrusive_ptr<SomeClass<T> > Create() {
return (new SomeClass)->GetPointer();
}
};

int main()
{
auto v = SomeClass<int>::Create();
}

带有 boost 1.41 的 GCC (4.4.1) 在实例化第一个(非常量)版本的 GetPointer() 时出现此错误:

error: call of overloaded ‘intrusive_ptr SharedObject<SomeClass<int> >* const)’ is ambiguous
boost/smart_ptr/intrusive_ptr.hpp:118: note: candidates are: boost::intrusive_ptr<T>::intrusive_ptr(boost::intrusive_ptr<T>&&) [with T = SomeClass<int>] <near match>
boost/smart_ptr/intrusive_ptr.hpp:94: note: boost::intrusive_ptr<T>::intrusive_ptr(const boost::intrusive_ptr<T>&) [with T = SomeClass<int>] <near match>
boost/smart_ptr/intrusive_ptr.hpp:70: note: boost::intrusive_ptr<T>::intrusive_ptr(T*, bool) [with T = SomeClass<int>] <near match>

以我的 C++ 技能不够深奥,我完全看不出为什么会有任何歧义。第 188 行和第 94 行的两个候选者采用现有的 intrusive_ptr 右值引用,SharedObject::this 当然不是。然而,最终的候选人是一个完美的匹配(bool 参数是可选的)。

谁愿意告诉我问题出在哪里?

EDIT+answer:我终于意识到在

  inline Pointer GetPointer() {
return Pointer(this); //Ambiguous call here
}

this 指的是 SharedObject 而 Pointer typedef 是 SomeClass。 (这几乎就是 Butterworth 马上指出的)。

  inline Pointer GetPointer() {
return Pointer(static_cast<C*>(this));
}

因为我知道 this 确实是 SomeClass,它继承自 SharedObject,因此 static_cast 使模板类“循环”。

最佳答案

当你说:

typedef boost::intrusive_ptr<T> Pointer;

当模板在您的代码中实例化。您的 SharedObject 类不是 int,因此您不能使用 this 实例化此类侵入式指针。

编辑:好的,我误解了你的代码,我会再试一次。在:

return Pointer(this); //Ambiguous call here

根据错误消息,这是一个 SharedObject ,但是我认为指针被类型定义为 SomeClass 。

您的代码非常难以理解 - 无论您想做什么,都必须有更简单的方法。而且您似乎在基类中缺少一个虚拟析构函数(可能还有一个虚拟函数)。

关于c++ - 使用类的 'this' 指针的 boost::intrusive_ptr 构造函数歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2116490/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com