【问题标题】:boost::intrusive_ptr constructor ambiguity using a class' 'this' pointerboost::intrusive_ptr 构造函数歧义使用类''this'指针
【发布时间】:2010-01-22 10:14:21
【问题描述】:

违规代码:

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。 (这几乎就是巴特沃思立即指出的)。

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

因为我知道this 确实是 SomeClass,从 SharedObject 继承,所以 static_cast 使模板类运转起来。

【问题讨论】:

    标签: c++ templates boost ambiguity


    【解决方案1】:

    当你说:

    typedef boost::intrusive_ptr<T> Pointer;
    

    当模板在您的代码中被实例化时,您正在声明一个类型,它是指向int 的侵入式指针(因为T 在那时是int)。您的 SharedObject 类不是 int,因此您无法使用 this 实例化这种侵入式指针。

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

    return Pointer(this); //Ambiguous call here
    

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

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

    【讨论】:

    • 我不确定我是否理解您的回答。我在原始问题中添加了一个更具体的示例。据我所知,ShareObject 是用SomeClass&lt;T&gt; 实例化的,作为 T 传递,据我所知,这使得typedef boost::intrusive_ptr&lt;T&gt; Pointer; 按预期工作?是我没听懂你的回答,还是我最初的例子太含糊了?
    • 感谢您的帮助。它帮助我解决了问题。

      至于我的目标,它实际上并不像看起来那么复杂。我把完整的课程放在paste.ubuntu.com/360614 以供参考。 (我没有错过虚拟析构函数 afaik)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多